Python Intermediate
Functions
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
def calculate_area(length, width):
return length * width
# Lambda functions
square = lambda x: x ** 2
print(square(5))
Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name}, {self.age} years old"
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def study(self):
return f"{self.name} is studying"
student = Student("Alice", 20, "A")
print(student.introduce())
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Error: {e}")
finally:
print("Cleanup code")
File Operations
# Reading files
with open("data.txt", "r") as file:
content = file.read()
# Writing files
with open("output.txt", "w") as file:
file.write("Hello, World!")