While Loop: Repeats a block of code while a condition is true.
x=0whilex<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:
defgreet(name):return"Hello, "+nameprint(greet("John"))# Output: Hello, John
Lambda (Anonymous) Functions:
square=lambdax:x*xprint(square(4))# Output: 16
6. Object-Oriented Programming (OOP) in Python
Key OOP Concepts:
Class & Object:
classPerson:def__init__(self,name,age):self.name=nameself.age=agedefgreet(self):returnf"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/0exceptZeroDivisionError:print("Cannot divide by zero")finally:print("Execution complete")
Used to modify functions without changing their code.
Example:
defdecorator_function(original_function):defwrapper_function():print("Wrapper executed before",original_function.__name__)returnoriginal_function()returnwrapper_function@decorator_functiondefdisplay():print("Display function executed")display()
11. Python’s map(), filter(), and reduce() Functions
Using map():
Applies a function to all elements of an iterable.
Top comments (0)