Here is a comprehensive Python guide that takes you through topics from complete beginner to
advanced expert level:
---
### **Beginner Level**
#### 1. **Introduction to Python**
- **What is Python?**
Python is an interpreted, high-level, general-purpose programming language. It is easy to
learn and has a simple syntax.
- **Installing Python**
Download from [python.org](https://www.python.org/) and install the latest version.
- **Hello, World!**
```python
print("Hello, World!")
```
#### 2. **Variables and Data Types**
- **Data Types**
Integer (`int`), Floating-point (`float`), String (`str`), Boolean (`bool`), List, Tuple, Dictionary,
Set.
1
- **Declaring Variables**
```python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
```
- **Basic Data Operations**
```python
x = 10 + 5 # Addition
y=x*2 # Multiplication
z = 10 / 3 # Division (float)
```
#### 3. **Control Flow (Conditionals and Loops)**
- **If-Else Statement**
```python
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
```
2
- **Loops**
- **For Loop**
```python
for i in range(5): # Loops from 0 to 4
print(i)
```
- **While Loop**
```python
count = 0
while count < 5:
print(count)
count += 1
```
#### 4. **Functions**
- **Defining a Function**
```python
def greet(name):
print(f"Hello, {name}!")
greet("Bob")
```
3
- **Return Values**
```python
def add(a, b):
return a + b
result = add(3, 4)
print(result)
```
---
### **Intermediate Level**
#### 5. **Data Structures**
- **Lists**
Lists are ordered and mutable.
```python
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adds to the list
```
- **Tuples**
Tuples are ordered and immutable.
```python
4
coordinates = (4, 5)
```
- **Dictionaries**
Dictionaries are unordered key-value pairs.
```python
person = {"name": "John", "age": 30}
person["age"] = 31 # Modifying value
```
- **Sets**
Sets are unordered collections of unique items.
```python
unique_numbers = {1, 2, 3, 3}
```
#### 6. **File Handling**
- **Reading a File**
```python
with open('file.txt', 'r') as file:
content = file.read()
print(content)
```
5
- **Writing to a File**
```python
with open('output.txt', 'w') as file:
file.write("Hello, World!")
```
#### 7. **Error Handling (Exceptions)**
- **Try-Except Block**
```python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```
- **Finally Block**
```python
try:
f = open("file.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
f.close()
```
6
---
### **Advanced Level**
#### 8. **Object-Oriented Programming (OOP)**
- **Classes and Objects**
```python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
print(f"The {self.brand} {self.model} is driving.")
car1 = Car("Toyota", "Corolla")
car1.drive()
```
- **Inheritance**
```python
class ElectricCar(Car):
def __init__(self, brand, model, battery_size):
7
super().__init__(brand, model)
self.battery_size = battery_size
def charge(self):
print(f"Charging {self.brand} {self.model} battery.")
electric_car = ElectricCar("Tesla", "Model 3", 75)
electric_car.charge()
```
#### 9. **Decorators**
- **Function Decorators**
```python
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
print("Hello!")
8
greet()
```
- **Class Decorators**
```python
def add_method(cls):
def new_method(self):
print("New method added")
cls.new_method = new_method
return cls
@add_method
class MyClass:
pass
obj = MyClass()
obj.new_method()
```
#### 10. **Generators and Iterators**
- **Generators**
```python
def count_up_to(max):
count = 1
9
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num)
```
- **Iterators**
```python
class Reverse:
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
10
rev = Reverse("giraffe")
for char in rev:
print(char)
```
#### 11. **Lambda Functions**
- **Anonymous Functions**
```python
add = lambda x, y: x + y
print(add(5, 7))
```
---
### **Expert Level**
#### 12. **Metaclasses**
- **Custom Metaclass**
```python
class MyMeta(type):
def __new__(cls, name, bases, dct):
dct['custom_method'] = lambda self: "Hello from the metaclass!"
return super().__new__(cls, name, bases, dct)
11
class MyClass(metaclass=MyMeta):
pass
obj = MyClass()
print(obj.custom_method()) # Output: Hello from the metaclass!
```
#### 13. **Concurrency and Parallelism**
- **Threading**
```python
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
```
- **Asyncio**
```python
12
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())
```
#### 14. **Advanced Python Libraries**
- **NumPy** (for numerical computations)
```python
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
```
- **Pandas** (for data manipulation)
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df)
```
13
- **Matplotlib** (for plotting)
```python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.show()
```
#### 15. **Design Patterns**
- **Singleton Pattern**
```python
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
```
---
### Additional Resources
14
- **Official Documentation**: [Python Docs](https://docs.python.org/)
- **Online Courses**:
- [Coursera Python for Everybody](https://www.coursera.org/specializations/python)
- [Udemy Python Courses](https://www.udemy.com/courses/search/?q=python)
- **Books**:
- *Automate the Boring Stuff with Python* by Al Sweigart
- *Fluent Python* by Luciano Ramalho
- *Python Crash Course* by Eric Matthes
This roadmap should help you gradually progress from beginner to advanced expert in Python!
15