Python programming basics
Python programming basics
Python is a high-level, interpreted, and general-purpose programming language. It's dynamically typed, meaning that you don't need to specify the data type of a variable when declaring it, and it uses indentation to define blocks of code. Here are some basics of Python programming:
Variables: In Python, you can assign values to variables using the equal (=) sign. For example:
x = 5
y = "Hello, World!"
Data types: Some common data types in Python include integers, floating-point numbers, strings, and Booleans. For example:
a = 5 # integer
b = 5.5 # floating-point number
c = "Hello" # string
d = True # Boolean
Operators: Python supports various arithmetic, comparison, and assignment operators. For example:
x = 5
y = 2
# Arithmetic operators
print(x + y) # 7
print(x - y) # 3
print(x * y) # 10
print(x / y) # 2.5
print(x % y) # 1
print(x ** y) # 25
# Comparison operators
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
# Assignment operators
x += y # x is now 7
x *= y # x is now 14
Conditional statements: You can use if statements to control the flow of your program based on conditions. For example:
x = 5
y = 2
if x > y:
print("x is greater than y")
else:
print("y is greater than or equal to x")
Loops: You can use for loops to iterate over a sequence (such as a list), and while loops to repeat a block of code as long as a certain condition is met. For example:
# For loop
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# While loop
i = 0
while i < 5:
print(i)
i += 1
# Output: 0 1 2 3 4
Functions: You can define your own functions in Python to encapsulate a piece of code that you want to reuse. For example:
def greet(name):
print("Hello, " + name + "!")
greet("John")
# Output: Hello, John!
Define a class:
pythonclass Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade def get_student_info(self): return f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}"
student = Student("John Doe", 20, "A")print(student.get_student_info())This example defines a class named Student with a constructor method (__init__) that takes three arguments (name, age, and grade) and initializes the instance variables name, age, and grade.
It also has a method named get_student_info that returns a string representation of the student information.
You can create an instance of the Student class by calling Student("John Doe", 20, "A") and assign it to a variable, student. And then you can call the method get_student_info on the student instance to get a string representation of the student information.
Comments
Post a Comment