Variables store data and do not require explicit type declaration.
Example:
x = 10 # Integer
y = "Python" # String
Operators:
Arithmetic:+, -, *, /, %, **, //
Comparison:==, !=, >, <, >=, <=
Logical:and, or, not
Assignment:=, +=, -=, *=, /=
Membership:in, not in
Identity:is, is not
4. Control Flow Statements
Conditional Statements:
Used for decision-making.
Example:
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Loops:
For Loop: Iterates over a sequence.
for i in range(5):
print(i) # Output: 0 1 2 3 4
While Loop: Repeats a block of code while a condition is true.
x = 0
while x < 5:
print(x)
x += 1
Loop Control Statements:
break → Exits the loop early.
continue → Skips the current iteration.
pass → Placeholder for future code.
5. Functions in Python
Functions help reuse code and improve modularity.
Example:
def greet(name):
return "Hello, " + name
print(greet("John")) # Output: Hello, John
Lambda (Anonymous) Functions:
square = lambda x: x * x
print(square(4)) # Output: 16
6. Object-Oriented Programming (OOP) in Python
Key OOP Concepts:
Class & Object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}"
p1 = Person("Alice", 25)
print(p1.greet()) # Output: Hello, my name is Alice
Encapsulation: Hiding data inside classes.
Inheritance: Reusing features of a parent class.
Polymorphism: Using a single method name for different types.
7. Exception Handling
Used to handle runtime errors.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
8. File Handling
Opening and Reading a File:
with open("file.txt", "r") as file:
content = file.read()
print(content)
Writing to a File:
with open("file.txt", "w") as file:
file.write("Hello, Python!")