Python supports object-oriented programming (OOP), which allows for code reusability and modularity.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f"Car: {self.brand} {self.model}")
# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display()
Inheritance allows one class to derive properties from another.
class Vehicle:
def __init__(self, brand):
self.brand = brand
def honk(self):
print("Honk! Honk!")
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
def display(self):
print(f"Car: {self.brand} {self.model}")
my_car = Car("Tesla", "Model S")
my_car.display()
my_car.honk()
Decorators allow you to modify the behavior of functions or classes dynamically.
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before", original_function.__name__)
return original_function()
return wrapper_function
@decorator_function
def say_hello():
print("Hello, World!")
say_hello()
Generators are functions that allow you to iterate over data lazily using the yield
keyword.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for num in count_up_to(5):
print(num)
Python’s threading
module allows for concurrent execution of code.
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
print("Thread finished execution")
Python allows reading and writing files easily.
with open("example.txt", "w") as file:
file.write("Hello, this is a test file!")
with open("example.txt", "r") as file:
content = file.read()
print(content)
Lambda functions are small, anonymous functions useful for short operations.
square = lambda x: x ** 2
print(square(5)) # Output: 25
Python's json
module is used to work with JSON data.
import json
data = {"name": "Alice", "age": 25}
json_data = json.dumps(data)
print(json_data)
import json
json_string = '{"name": "Alice", "age": 25}'
data = json.loads(json_string)
print(data["name"]) # Output: Alice
Python's re
module is used for pattern matching.
import re
pattern = r"\d{3}-\d{2}-\d{4}"
text = "My number is 123-45-6789"
match = re.search(pattern, text)
if match:
print("Match found:", match.group())
Python allows handling errors gracefully using try-except
.
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute.")
Python has built-in support for SQLite databases.
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
conn.commit()
conn.close()
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
conn.close()
Now that you've explored advanced Python concepts, you're ready to take on real-world projects and optimize your code for performance!
Want to review the basics? Check out our Basic Python Tutorial.
Test Your Knowledge Here
Test Your Coding Skills Here