Python is a high-level, interpreted programming language known for readability and versatility.
Purpose: Write clear, logical code for projects big and small.
is_active = True
age = 30
pi = 3.1415
name = "Alice"
items = [1, 2, 3]
info = {"key": "value"}
data = None
Purpose: Store different types of data appropriately.
message = "Hello World" # Python infers the type
Purpose: Write clean code without explicit type declarations.
def add(a, b):
return a + b
Purpose: Reuse logic without repeating code.
if age > 18:
print("Adult")
elif age == 18:
print("Just became adult")
else:
print("Minor")
Purpose: Make decisions based on conditions.
for item in items:
print(item)
while age > 0:
age -= 1
Purpose: Repeat actions multiple times.
squares = [x**2 for x in range(5)]
Purpose: Create lists quickly and concisely.
person = {"name": "Alice", "age": 30}
print(person["name"])
Purpose: Store key-value pairs for quick lookup.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")
p = Person("Alice")
p.greet()
Purpose: Organize code using Object-Oriented Programming (OOP).
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
Purpose: Reuse and extend functionality across classes.
# math_module.py
def add(a, b):
return a + b
# app.py
import math_module
print(math_module.add(2, 3))
Purpose: Organize and reuse code across multiple files.
try:
1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("End of operation")
Purpose: Handle errors gracefully without crashing.
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def greet():
print("Hello")
greet()
Purpose: Extend or modify function behavior.
add = lambda x, y: x + y
print(add(2, 3))
Purpose: Create small anonymous functions inline.
nums = [1, 2, 3]
doubled = list(map(lambda x: x*2, nums))
Purpose: Perform common tasks easily.
def greet(name: str) -> str:
return f"Hello, {name}"
Purpose: Improve code readability and tooling support.
python -m venv myenv
source myenv/bin/activate # Mac/Linux
myenv\Scripts\activate # Windows
Purpose: Isolate project dependencies.
Purpose: Extend Python capabilities quickly.
*args, **kwargs — Flexible argumentswith — Context management