Python Mastery Guide
Python Mastery Guide
Table of Contents
1. Introduction to Python
2. Python Fundamentals
3. Data Structures
4. Control Flow and Loops
5. Functions and Modules
6. Object-Oriented Programming
7. File Handling and I/O
8. Exception Handling
9. Advanced Python Features
10. Working with Libraries
11. Best Practices and Patterns
12. Real-World Projects
13. Performance Optimization
14. Testing and Debugging
15. Deployment and Automation
---
1. Introduction to Python
Why Python?
Python has become the world's most popular programming language for several compelling
reasons:
Simple and Readable**: Python's syntax is designed to be intuitive and easy to read,
making it accessible to beginners while powerful enough for experts.
Versatile**: From web development to data science, machine learning to automation,
Python does it all.
Massive Ecosystem**: Over 300,000 packages available on PyPI for virtually any task.
Strong Community**: Millions of developers worldwide contribute to its growth and
improvement.
High Demand**: Python consistently ranks as one of the most sought-after skills in the
job market.
Readability counts.
reated by Guido van Rossum in 1991, Python was designed with the
philosophy that "code is read much more often than it is
written." This principle is embodied in The Zen of Python:
Installation
Windows:
macOS:
*Windows:**
1. Download Python from [Link]
2. Run the installer
3. **CRITICAL**: Check "Add Python to PATH"
4. Verify installation: `python --version`
**macOS:**
*Windows:**
1. Download Python from [Link]
2. Run the installer
3. **CRITICAL**: Check "Add Python to PATH"
4. Verify installation: `python --version`
**macOS:**
Linux:
*Windows:**
1. Download Python from [Link]
2. Run the installer
3. **CRITICAL**: Check "Add Python to PATH"
4. Verify installation: `python --version`
**macOS:**
*Windows:**
1. Download Python from [Link]
2. Run the installer
3. **CRITICAL**: Check "Add Python to PATH"
4. Verify installation: `python --version`
**macOS:**
Essential Tools
Virtual Environments:
*Virtual Environments:**
myenv\Scripts\activate # Windows
*Virtual Environments:**
Package Management:
*Virtual Environments:**
*Virtual Environments:**
Code Editors:
VS Code (recommended)
PyCharm (professional IDE)
Jupyter Notebook (data science)
---
2. Python Fundamentals
Numbers
integer = 42
float_num = 3.14159
complex_num = 3 + 4j
Strings
name = "Python"
multiline = """This is a
multi-line string"""
Booleans
is_active = True
is_complete = False
String Operations
```python
String methods
print([Link]()) # python programming
String formatting
name = "Alice"
age = 25
me = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
print("My name is {} and I'm {} years old".format(name, age))
Basic operations
a, b = 10, 3
print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a % b) # 1 (modulo)
Math module
import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
print([Link]([Link]/2)) # 1.0
print([Link](3.2)) # 4
print([Link](3.8)) # 3
port math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
print([Link]([Link]/2)) # 1.0
print([Link](3.2)) # 4
print([Link](3.8)) # 3
Type Conversion
```python
num_int = int(num_str) # 42
Checking types
print(type(42)) # <class 'int'>
---
3. Data Structures
Lists
Lists are ordered, mutable collections that can hold any type of data.
ists are ordered, mutable collections that can hold any type of
data.
Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
Accessing elements
print(fruits[0]) # apple
Modifying lists
[Link]("orange") # Add to end
List operations
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
List comprehensions
squares = [x**2 for x in range(10)]
Common methods
print(len(numbers)) # Length
print(max(numbers)) # Maximum
print(min(numbers)) # Minimum
print(sum(numbers)) # Sum
int(len(numbers)) # Length
print(max(numbers)) # Maximum
print(min(numbers)) # Minimum
print(sum(numbers)) # Sum
print([Link](1)) # Count occurrences
print([Link](5)) # Find index
Tuples
Tuples are ordered, immutable collections.
Creating tuples
coordinates = (10, 20)
Accessing elements
print(coordinates[0]) # 10
Tuple unpacking
x, y = coordinates
r, g, b = colors
p = Point(10, 20)
print(p.x, p.y) # 10 20
Dictionaries
Dictionaries are key-value pairs, unordered (in Python 3.7+ they maintain insertion order).
Creating dictionaries
person = {
"name": "Alice",
"age": 25,
Accessing values
print(person["name"]) # Alice
print([Link]("age")) # 25
Modifying dictionaries
person["email"] = "alice@[Link]" # Add key
Dictionary methods
print([Link]()) # dict_keys(['name', 'age', 'email'])
Dictionary comprehensions
squares = {x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```
Sets
Sets are unordered collections of unique elements.
Creating sets
numbers = {1, 2, 3, 4, 5}
Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
Set methods
[Link](6) # Add element
Checking membership
print(3 in numbers) # True
---
Conditional Statements
```python
age = 18
print("Child")
print("Teenager")
print("Adult")
else:
print("Senior")
Ternary operator
status = "Adult" if age >= 18 else "Minor"
Multiple conditions
x, y = 10, 20
if not x < 5:
y = 10, 20
if x > 5 and y > 15:
print("Both conditions true")
if not x < 5:
print("x is not less than 5")
For Loops
```python
print(fruit)
Using range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
print(i)
Enumerate (get index and value)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Dictionary iteration
person = {"name": "Alice", "age": 25}
print(key)
print(value)
print(f"{key}: {value}")
Loop control
for i in range(10):
if i == 3:
if i == 7:
print(i)
r i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit the loop
print(i)
While Loops
```python
print(count)
count += 1
print(count)
count += 1
else:
print("Loop completed")
if user_input.lower() == 'quit':
break
ile True:
user_input = input("Enter 'quit' to exit: ")
if user_input.lower() == 'quit':
break
print(f"You entered: {user_input}")
Advanced Loop Patterns
```python
Nested loops
for i in range(3):
for j in range(3):
print(f"({i}, {j})")
Dictionary comprehension
word = "hello"
---
5. Functions and Modules
Defining Functions
```python
Basic function
def greet():
print("Hello, World!")
greet()
print(f"Hello, {name}!")
greet_person("Alice")
return a + b
result = add(5, 3)
print(result) # 8
Default parameters
def greet_with_title(name, title="Mr."):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
def print_info(**kwargs):
print(f"{key}: {value}")
f sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
Lambda Functions
```python
print(add(3, 4)) # 7
Lambda in sorting
students = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
def my_function():
x = 5 # Local variable
print(f"Local x: {x}")
my_function()
print(f"Global x: {x}")
Using global keyword
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Closures
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
add_five = outer_function(5)
print(add_five(3)) # 8
f outer_function(x):
def inner_function(y):
return x + y
return inner_function
add_five = outer_function(5)
print(add_five(3)) # 8
Importing modules
import math
print([Link](16))
Importing specific functions
from math import sqrt, pi
print(sqrt(25))
print(pi)
import pandas as pd
PI = 3.14159
print([Link]("Alice"))
print([Link])
Decorators
```python
Basic decorator
def my_decorator(func):
def wrapper():
func()
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
import time
start = [Link]()
end = [Link]()
return result
return wrapper
@timer
def slow_function():
import time
[Link](1)
return "Done"
slow_function()
f timer(func):
import time
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end - start:.2f} seconds")
return result
return wrapper
@timer
def slow_function():
import time
[Link](1)
return "Done"
slow_function()
---
6. Object-Oriented Programming
Defining a class
class Person:
[Link] = age
def greet(self):
[Link] += 1
Creating objects
person1 = Person("Alice", 25)
print([Link]) # Alice
print([Link]) # Alice
print([Link]()) # Hello, my name is Alice
print(person1.have_birthday()) # Happy 26th birthday!
class Car:
wheels = 4
# Instance attributes
[Link] = make
[Link] = model
[Link] = year
[Link] = 0
# Instance method
def drive(self, miles):
[Link] += miles
# Class method
@classmethod
# Static method
@staticmethod
def is_valid_year(year):
print([Link]) # 4
print([Link]) # 100
print(Car.is_valid_year(1800)) # False
int(Car.is_valid_year(2020)) # True
print(Car.is_valid_year(1800)) # False
Inheritance
```python
Parent class
class Animal:
[Link] = name
def speak(self):
Child classes
class Dog(Animal):
def speak(self):
class Cat(Animal):
def speak(self):
Using inheritance
dog = Dog("Buddy")
cat = Cat("Whiskers")
[Link] = brand
def start(self):
class ElectricCar(Vehicle):
self.battery_capacity = battery_capacity
def start(self):
def charge(self):
ass Vehicle:
def __init__(self, brand):
[Link] = brand
def start(self):
return f"{[Link]} vehicle starting..."
class ElectricCar(Vehicle):
def __init__(self, brand, battery_capacity):
super().__init__(brand) # Call parent's __init__
self.battery_capacity = battery_capacity
def start(self):
return f"{[Link]} electric car starting silently..."
def charge(self):
return f"Charging {self.battery_capacity}kWh battery"
tesla = ElectricCar("Tesla", 75)
print([Link]()) # Tesla electric car starting silently...
print([Link]()) # Charging 75kWh battery
@property
def balance(self):
return self.__balance
@[Link]
def balance(self, value):
if value >= 0:
self.__balance = value
else:
raise ValueError("Balance cannot be negative")
class BankAccount:
if amount > 0:
self.__balance += amount
self.__balance -= amount
@property
def balance(self):
return self.__balance
@[Link]
if value >= 0:
self.__balance = value
else:
print([Link]) # 1300
``python
class BankAccount:
def __init__(self, owner, balance=0):
[Link] = owner
self.__balance = balance # Private attribute (name
mangling)
@property
def balance(self):
return self.__balance
@[Link]
def balance(self, value):
if value >= 0:
self.__balance = value
else:
raise ValueError("Balance cannot be negative")
def __repr__(self):
return f"Vector(x={self.x}, y={self.y})"
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1) # Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(len(v1)) # 5
print(v1 == Vector(3, 4)) # True
class Vector:
self.x = x
self.y = y
def __str__(self):
def __repr__(self):
def __len__(self):
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1) # Vector(3, 4)
print(len(v1)) #5
``python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __repr__(self):
return f"Vector(x={self.x}, y={self.y})"
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1) # Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(len(v1)) # 5
print(v1 == Vector(3, 4)) # True
---
7. File Handling and I/O
Reading files
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
print([Link]())
lines = [Link]()
print(lines)
Writing files
with open('[Link]', 'w') as file:
[Link]("Hello, World!\n")
Appending to files
with open('[Link]', 'a') as file:
[Link]("\nThis line is appended.")
[Link](lines)
import csv
Reading CSV
with open('[Link]', 'r') as file:
reader = [Link](file)
print(row)
reader = [Link](file)
print(row['name'], row['age'])
Writing CSV
data = [
['name', 'age', 'city'],
writer = [Link](file)
[Link](data)
[Link]()
import json
Reading JSON
with open('[Link]', 'r') as file:
data = [Link](file)
print(data)
Writing JSON
data = {
"name": "Alice",
"age": 25,
"city": "NYC"
JSON to string
json_string = [Link](data, indent=2)
print(json_string)
String to JSON
parsed = [Link](json_string)
print(parsed)
rsed = [Link](json_string)
print(parsed)
import os
import shutil
print(current_dir)
print(files)
Create directory
[Link]('new_folder', exist_ok=True)
print([Link]('[Link]'))
print([Link]('new_folder'))
Join paths
path = [Link]('folder', 'subfolder', '[Link]')
print(path)
path = Path('folder/subfolder/[Link]')
print([Link]) # folder/subfolder
print([Link]) # [Link]
print([Link]) # file
print([Link]) # .txt
Create directories
Path('new_folder').mkdir(exist_ok=True)
List files
for file in Path('.').iterdir():
print(file)
r file in Path('.').iterdir():
print(file)
---
8. Exception Handling
Try-except block
try:
result = 10 / 0
except ZeroDivisionError:
Multiple exceptions
try:
result = 10 / number
except ValueError:
except Exception as e:
content = [Link]()
except FileNotFoundError:
else:
print(content)
finally:
if 'file' in locals():
[Link]()
print("Cleanup complete!")
y:
file = open('[Link]', 'r')
content = [Link]()
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully!")
print(content)
finally:
if 'file' in locals():
[Link]()
print("Cleanup complete!")
Raising Exceptions
```python
Raising exceptions
def divide(a, b):
if b == 0:
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")
Custom exceptions
class InvalidAgeError(Exception):
[Link] = age
[Link] = message
super().__init__([Link])
def set_age(age):
raise InvalidAgeError(age)
try:
print(set_age(150))
except InvalidAgeError as e:
print(f"Invalid age {[Link]}: {[Link]}")
ass InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 0 and
120"):
[Link] = age
[Link] = message
super().__init__([Link])
def set_age(age):
if not 0 <= age <= 120:
raise InvalidAgeError(age)
return f"Age set to {age}"
try:
print(set_age(150))
except InvalidAgeError as e:
print(f"Invalid age {[Link]}: {[Link]}")
# Some operation
pass
except Exception as e:
import traceback
traceback.print_exc()
Context managers for resource
management
with open('[Link]', 'r') as file:
content = [Link]()
[Link](filename='[Link]', level=[Link])
try:
result = 10 / 0
except Exception as e:
port logging
[Link](filename='[Link]', level=[Link])
try:
result = 10 / 0
except Exception as e:
[Link](f"An error occurred: {e}", exc_info=True)
---
Generators
```python
Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
Using generator
for i in countdown(5):
print(i) # 5, 4, 3, 2, 1
Generator expression
squares = (x**2 for x in range(10))
print(square)
yield [Link]()
process(line)
r line in read_large_file('large_file.txt'):
process(line)
Iterators
```python
[Link] = start
def __iter__(self):
return self
def __next__(self):
if [Link] <= 0:
raise StopIteration
current = [Link]
[Link] -= 1
return current
for i in countdown:
print(i)
Itertools module
import itertools
Infinite iterator
counter = [Link](start=0, step=2)
for i in range(5):
print(next(counter)) # 0, 2, 4, 6, 8
Cycle
colors = [Link](['red', 'green', 'blue'])
for i in range(5):
Combinations
items = ['A', 'B', 'C']
Context Managers
```python
[Link] = filename
[Link] = mode
[Link] = None
def __enter__(self):
if [Link]:
[Link]()
if exc_type:
content = [Link]()
print(content)
@contextmanager
def timer():
import time
start = [Link]()
yield
end = [Link]()
with timer():
# Some operation
import time
[Link](1)
om contextlib import contextmanager
@contextmanager
def timer():
import time
start = [Link]()
yield
end = [Link]()
print(f"Elapsed time: {end - start:.2f} seconds")
with timer():
# Some operation
import time
[Link](1)
Metaclasses
```python
Simple metaclass
class SingletonMeta(type):
_instances = {}
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
def __init__(self):
[Link] = 0
s2 = Singleton()
class MyClass(metaclass=AddMethodMeta):
pass
obj = MyClass()
ass AddMethodMeta(type):
def __new__(cls, name, bases, namespace):
namespace['greet'] = lambda self: f"Hello from {name}"
return super().__new__(cls, name, bases, namespace)
class MyClass(metaclass=AddMethodMeta):
pass
obj = MyClass()
print([Link]()) # Hello from MyClass
---
import numpy as np
Creating arrays
arr = [Link]([1, 2, 3, 4, 5])
print([Link](arr)) # 3.0
print([Link](arr)) # 1.414...
Array slicing
print(arr[1:4]) # [2, 3, 4]
Mathematical functions
print([Link](arr))
print([Link](arr))
print([Link](arr))
Random numbers
print([Link](5)) # 5 random numbers [0, 1)
import pandas as pd
Creating DataFrames
data = {
df = [Link](data)
Reading data
df = pd.read_csv('[Link]')
df = pd.read_excel('[Link]')
df = pd.read_json('[Link]')
Data exploration
print([Link]()) # First 5 rows
Data selection
print(df['name']) # Single column
print(filtered)
Data manipulation
df['new_column'] = df['age'] * 2
df = [Link]('new_column', axis=1)
print(grouped['age'].mean())
Sorting
df_sorted = df.sort_values('age', ascending=False)
Line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('X axis')
[Link]('Y axis')
[Link]('Line Plot')
[Link]()
Bar chart
categories = ['A', 'B', 'C', 'D']
[Link](categories, values)
[Link]('Bar Chart')
[Link]()
Scatter plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 3, 5]
[Link](x, y)
[Link]('Scatter Plot')
[Link]()
Histogram
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
[Link](data, bins=5)
[Link]('Histogram')
[Link]()
Multiple plots
fig, axes = [Link](2, 2)
axes[0, 0].plot(x, y)
axes[1, 0].scatter(x, y)
axes[1, 1].hist(data)
plt.tight_layout()
[Link]()
g, axes = [Link](2, 2)
axes[0, 0].plot(x, y)
axes[0, 1].bar(categories, values)
axes[1, 0].scatter(x, y)
axes[1, 1].hist(data)
plt.tight_layout()
[Link]()
import requests
GET request
response = [Link]('[Link]
print(response.status_code) # 200
POST request
data = {'name': 'Alice', 'age': 25}
print(response.status_code)
Headers and parameters
headers = {'Authorization': 'Bearer token'}
response = [Link]('[Link]
headers=headers, params=params)
Error handling
try:
response = [Link]('[Link]
except [Link] as e:
y:
response = [Link]('[Link]
response.raise_for_status() # Raise exception for bad status
codes
except [Link] as e:
print(f"Request failed: {e}")
---
if not numbers:
return 0
Bad
def calcAvg(n):
a=0
for i in n:
a+=i
return a/len(n)
Docstrings
def complex_function(param1, param2):
"""
Args:
Returns:
Raises:
"""
pass
f complex_function(param1, param2):
"""
Brief description of the function.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of return value
Raises:
ValueError: If something goes wrong
"""
pass
Design Patterns
```python
Singleton Pattern
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
Factory Pattern
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == 'dog':
return Dog()
return Cat()
else:
Observer Pattern
class Observer:
pass
class Subject:
def __init__(self):
self._observers = []
self._observers.append(observer)
[Link](message)
Strategy Pattern
class PaymentStrategy:
pass
class CreditCardPayment(PaymentStrategy):
class PayPalPayment(PaymentStrategy):
ass PaymentStrategy:
def pay(self, amount):
pass
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paid ${amount} with credit card")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paid ${amount} with PayPal")
Performance Optimization
```python
Slow
sum_slow = 0
Fast
sum_fast = sum(numbers)
squares_slow.append(num ** 2)
Fast
squares_fast = [num ** 2 for num in range(1000)]
Memory efficient
def get_squares_generator(n):
for x in range(n):
yield x**2
pass
pass
def my_function():
pass
[Link]('my_function()')
port cProfile
def my_function():
# Your code here
pass
[Link]('my_function()')
---
12. Real-World Projects
Web Scraper
``python
import requests
from bs4 import BeautifulSoup
import pandas as pd
def scrape_quotes():
"""Scrape quotes from a website."""
url = '[Link]
quotes = []
[Link]({
'text': text,
'author': author,
'tags': ', '.join(tags)
})
# Save to CSV
df = [Link](quotes)
df.to_csv('[Link]', index=False)
print(f"Scraped {len(quotes)} quotes")
scrape_quotes()
import requests
import pandas as pd
def scrape_quotes():
quotes = []
response = [Link](f'{url}/page/{page}')
[Link]({
'text': text,
'author': author,
})
# Save to CSV
df = [Link](quotes)
df.to_csv('[Link]', index=False)
scrape_quotes()
``python
import requests
from bs4 import BeautifulSoup
import pandas as pd
def scrape_quotes():
"""Scrape quotes from a website."""
url = '[Link]
quotes = []
[Link]({
'text': text,
'author': author,
'tags': ', '.join(tags)
})
# Save to CSV
df = [Link](quotes)
df.to_csv('[Link]', index=False)
print(f"Scraped {len(quotes)} quotes")
scrape_quotes()
def analyze_sales_data():
"""Analyze sales data and create visualizations."""
# Load data
df = pd.read_csv('sales_data.csv')
# Data cleaning
df['date'] = pd.to_datetime(df['date'])
df = [Link]()
# Basic statistics
print("Sales Statistics:")
print(df['amount'].describe())
# Monthly sales
df['month'] = df['date'].[Link]
monthly_sales = [Link]('month')['amount'].sum()
# Visualization
[Link](figsize=(12, 6))
monthly_sales.plot(kind='bar')
[Link]('Monthly Sales')
[Link]('Month')
[Link]('Sales Amount')
[Link]('monthly_sales.png')
# Top products
top_products = [Link]('product')
['amount'].sum().sort_values(ascending=False).head(10)
[Link](figsize=(12, 6))
top_products.plot(kind='barh')
[Link]('Top 10 Products by Sales')
[Link]('Sales Amount')
[Link]('top_products.png')
print("Analysis complete!")
analyze_sales_data()
import pandas as pd
def analyze_sales_data():
# Load data
df = pd.read_csv('sales_data.csv')
# Data cleaning
df['date'] = pd.to_datetime(df['date'])
df = [Link]()
# Basic statistics
print("Sales Statistics:")
print(df['amount'].describe())
# Monthly sales
df['month'] = df['date'].[Link]
monthly_sales = [Link]('month')['amount'].sum()
# Visualization
[Link](figsize=(12, 6))
monthly_sales.plot(kind='bar')
[Link]('Monthly Sales')
[Link]('Month')
[Link]('Sales Amount')
[Link]('monthly_sales.png')
# Top products
top_products = [Link]('product')
['amount'].sum().sort_values(ascending=False).head(10)
[Link](figsize=(12, 6))
top_products.plot(kind='barh')
[Link]('Sales Amount')
[Link]('top_products.png')
print("Analysis complete!")
analyze_sales_data()
``python
import pandas as pd
import [Link] as plt
import seaborn as sns
def analyze_sales_data():
"""Analyze sales data and create visualizations."""
# Load data
df = pd.read_csv('sales_data.csv')
# Data cleaning
df['date'] = pd.to_datetime(df['date'])
df = [Link]()
# Basic statistics
print("Sales Statistics:")
print(df['amount'].describe())
# Monthly sales
df['month'] = df['date'].[Link]
monthly_sales = [Link]('month')['amount'].sum()
# Visualization
[Link](figsize=(12, 6))
monthly_sales.plot(kind='bar')
[Link]('Monthly Sales')
[Link]('Month')
[Link]('Sales Amount')
[Link]('monthly_sales.png')
# Top products
top_products = [Link]('product')
['amount'].sum().sort_values(ascending=False).head(10)
[Link](figsize=(12, 6))
top_products.plot(kind='barh')
[Link]('Top 10 Products by Sales')
[Link]('Sales Amount')
[Link]('top_products.png')
print("Analysis complete!")
analyze_sales_data()
Automation Script
``python
import os
import shutil
from datetime import datetime
def organize_downloads():
"""Organize files in Downloads folder by type."""
downloads_path = [Link]('~/Downloads')
if [Link](file_path):
file_ext = [Link](filename)[1].lower()
print("Downloads organized!")
organize_downloads()
import os
import shutil
def organize_downloads():
downloads_path = [Link]('~/Downloads')
categories = {
[Link](category_path, exist_ok=True)
if [Link](file_path):
file_ext = [Link](filename)[1].lower()
if file_ext in extensions:
[Link](file_path, dest_path)
break
print("Downloads organized!")
organize_downloads()
``python
import os
import shutil
from datetime import datetime
def organize_downloads():
"""Organize files in Downloads folder by type."""
downloads_path = [Link]('~/Downloads')
if [Link](file_path):
file_ext = [Link](filename)[1].lower()
print("Downloads organized!")
organize_downloads()
API Integration
```python
import requests
import pandas as pd
base_url = "[Link]
params = {
'q': city,
'appid': api_key,
'units': 'metric'
if response.status_code == 200:
data = [Link]()
weather_info = {
'city': data['name'],
'temperature': data['main']['temp'],
'feels_like': data['main']['feels_like'],
'humidity': data['main']['humidity'],
'description': data['weather'][0]['description'],
return weather_info
else:
print(f"Error: {response.status_code}")
return None
weather_data = []
for _ in range(duration_hours):
for city in cities:
if data:
weather_data.append(data)
# [Link](3600)
# Save to CSV
df = [Link](weather_data)
df.to_csv('weather_data.csv', index=False)
Usage
cities = ['New York', 'London', 'Tokyo']
api_key = 'your_api_key_here'
track_weather(cities, api_key)
---
import time
import cProfile
import timeit
Simple timing
def measure_time(func):
start = [Link]()
end = [Link]()
return result
return wrapper
@measure_time
def slow_function():
total = 0
for i in range(1000000):
total += i
return total
slow_function()
Using timeit
code = """
sum(range(1000000))
"""
Using cProfile
def profile_function():
total = 0
for i in range(1000000):
total += i ** 2
return total
[Link]('profile_function()')
f profile_function():
total = 0
for i in range(1000000):
total += i ** 2
return total
[Link]('profile_function()')
Memory Optimization
```python
import sys
import gc
return [Link](obj)
Generator vs List
def list_version(n):
def generator_version(n):
list_size = get_size(list_version(1000000))
print(f"List size: {list_size} bytes")
Garbage collection
class MyClass:
def __del__(self):
print("Object deleted")
obj = MyClass()
obj = MyClass()
del obj # Explicit deletion
[Link]() # Force garbage collection
Algorithm Optimization
```python
duplicates = []
for i in range(len(arr)):
[Link](arr[i])
return duplicates
O(n) - Fast
def find_duplicates_fast(arr):
seen = set()
duplicates = set()
if item in seen:
[Link](item)
else:
[Link](item)
return list(duplicates)
Benchmark
import timeit
port timeit
import time
Without caching
def fibonacci_slow(n):
if n <= 1:
return n
def fibonacci_fast(n):
if n <= 1:
return n
Benchmark
start = [Link]()
result = fibonacci_slow(35)
start = [Link]()
result = fibonacci_fast(35)
Custom memoization
def memoize(func):
cache = {}
def wrapper(*args):
return cache[args]
return wrapper
@memoize
def expensive_function(x):
[Link](0.1)
return x ** 2
result1 = expensive_function(5)
result2 = expensive_function(5)
art = [Link]()
result2 = expensive_function(5)
second_time = [Link]() - start
---
14. Testing and Debugging
class TestMathFunctions([Link]):
def test_add(self):
[Link](add(2, 3), 5)
[Link](add(-1, 1), 0)
[Link](add(0, 0), 0)
def test_divide(self):
[Link](divide(10, 2), 5)
[Link](divide(-10, 2), -5)
def test_divide_by_zero(self):
with [Link](ValueError):
divide(10, 0)
if __name__ == '__main__':
[Link]()
import unittest
return a + b
if b == 0:
return a / b
class TestMathFunctions([Link]):
def test_add(self):
[Link](add(2, 3), 5)
[Link](add(-1, 1), 0)
[Link](add(0, 0), 0)
def test_divide(self):
[Link](divide(10, 2), 5)
def test_divide_by_zero(self):
with [Link](ValueError):
divide(10, 0)
if __name__ == '__main__':
[Link]()
``python
import unittest
class TestMathFunctions([Link]):
def test_add(self):
[Link](add(2, 3), 5)
[Link](add(-1, 1), 0)
[Link](add(0, 0), 0)
def test_divide(self):
[Link](divide(10, 2), 5)
[Link](divide(-10, 2), -5)
def test_divide_by_zero(self):
with [Link](ValueError):
divide(10, 0)
if __name__ == '__main__':
[Link]()
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_divide():
assert divide(10, 2) == 5
assert divide(-10, 2) == -5
def test_divide_by_zero():
with [Link](ValueError):
divide(10, 0)
@[Link]("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
])
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
import pytest
return a + b
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_divide():
assert divide(10, 2) == 5
assert divide(-10, 2) == -5
def test_divide_by_zero():
with [Link](ValueError):
divide(10, 0)
@[Link]("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
])
``python
import pytest
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_divide():
assert divide(10, 2) == 5
assert divide(-10, 2) == -5
def test_divide_by_zero():
with [Link](ValueError):
divide(10, 0)
@[Link]("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
])
def test_add_parametrized(a, b, expected):
assert add(a, b) == expected
Debugging Techniques
```python
print(f"Input: {x}")
result = x ** 2
print(f"Result: {result}")
return result
def debug_with_pdb(x):
pdb.set_trace() # Breakpoint
result = x ** 2
return result
[Link](
level=[Link],
def log_function(x):
result = x ** 2
[Link](f"Result: {result}")
return result
try:
return a / b
except Exception as e:
[Link](traceback.format_exc())
raise
port traceback
Args:
Returns:
Raises:
Example:
calculate_metrics([1, 2, 3, 4, 5])
"""
if not data:
import statistics
return {
'mean': [Link](data),
'median': [Link](data),
'std': [Link](data)
Args:
data: A list of numerical values.
Returns:
A dictionary containing mean, median, and std.
Raises:
ValueError: If data is empty.
Example:
>>> calculate_metrics([1, 2, 3, 4, 5])
{'mean': 3.0, 'median': 3.0, 'std': 1.414...}
"""
if not data:
raise ValueError("Data cannot be empty")
import statistics
return {
'mean': [Link](data),
'median': [Link](data),
'std': [Link](data)
}
---
Virtual Environments
```bash
Activate (Windows)
myenv\Scripts\activate
Activate (macOS/Linux)
source myenv/bin/activate
Install packages
pip install numpy pandas requests
Export requirements
pip freeze > [Link]
Deactivate
deactivate
activate
import argparse
import sys
def main():
parser = [Link](
description='Process data files'
)
parser.add_argument(
'input',
help='Input file path'
)
parser.add_argument(
'-o', '--output',
default='[Link]',
help='Output file path (default: [Link])'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose output'
)
args = parser.parse_args()
if [Link]:
print(f"Input: {[Link]}")
print(f"Output: {[Link]}")
try:
process_file([Link], [Link])
except Exception as e:
print(f"Error: {e}", file=[Link])
[Link](1)
if __name__ == '__main__':
main()
#!/usr/bin/env python3
"""
"""
import argparse
import sys
print(f"Processing {input_file}...")
print(f"Saved to {output_file}")
def main():
parser = [Link](
description='Process data files'
parser.add_argument(
'input',
parser.add_argument(
'-o', '--output',
default='[Link]',
parser.add_argument(
'-v', '--verbose',
action='store_true',
args = parser.parse_args()
if [Link]:
print(f"Input: {[Link]}")
print(f"Output: {[Link]}")
try:
process_file([Link], [Link])
except Exception as e:
[Link](1)
if __name__ == '__main__':
main()
``python
#!/usr/bin/env python3
"""
Main script for data processing application.
"""
import argparse
import sys
def main():
parser = [Link](
description='Process data files'
)
parser.add_argument(
'input',
help='Input file path'
)
parser.add_argument(
'-o', '--output',
default='[Link]',
help='Output file path (default: [Link])'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose output'
)
args = parser.parse_args()
if [Link]:
print(f"Input: {[Link]}")
print(f"Output: {[Link]}")
try:
process_file([Link], [Link])
except Exception as e:
print(f"Error: {e}", file=[Link])
[Link](1)
if __name__ == '__main__':
main()
Task Scheduling
```python
import schedule
import time
def job():
def backup_data():
print("Backing up data...")
Schedule jobs
[Link](10).[Link](job)
[Link]().[Link](job)
[Link]().[Link]("10:30").do(job)
[Link]().[Link](backup_data)
schedule.run_pending()
[Link](1)
scheduler = BlockingScheduler()
[Link]()
def scheduled_task():
print("Task executed at", [Link]())
scheduler = BlockingScheduler()
scheduler.add_job(scheduled_task, 'interval', minutes=30)
[Link]()
Dockerfile
FROM python:3.9-slim
WORKDIR /app
D ["python", "[Link]"]
D ["python", "[Link]"]
[Link]
version: '3.8'
services:
web:
build: .
ports:
"8000:8000"
volumes:
.:/app
environment:
DEBUG=True
DATABASE_URL=postgresql://user:pass@db:5432/mydb
db:
image: postgres:13
environment:
POSTGRES_USER=user
POSTGRES_PASSWORD=pass
POSTGRES_DB=mydb
volumes:
postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
rsion: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
volumes:
- .:/app
environment:
- DEBUG=True
- DATABASE_URL=postgresql://user:pass@db:5432/mydb
db:
image: postgres:13
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass
- POSTGRES_DB=mydb
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
.github/workflows/[Link]
name: Python Application
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
uses: actions/checkout@v2
name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
run: |
run: |
uses: codecov/codecov-action@v2
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
---
Conclusion
This comprehensive guide has covered the essential aspects of Python programming, from
basic syntax to advanced concepts and real-world applications. Python's simplicity and
power make it an excellent choice for beginners and experts alike.
Key Takeaways:
20. **Master the Fundamentals**: Variables, data types, control flow, and functions form
the foundation.
21. **Embrace Object-Oriented Programming**: Classes, inheritance, and polymorphism
enable code organization and reuse.
22. **Leverage the Ecosystem**: NumPy, Pandas, and other libraries provide powerful tools
for specific tasks.
23. **Write Clean Code**: Follow PEP 8 guidelines, use meaningful names, and document
your code.
24. **Test Thoroughly**: Unit tests and debugging ensure code reliability.
25. **Optimize When Necessary**: Profile before optimizing, and use appropriate data
structures.
26. **Automate Everything**: Use scripts, schedulers, and CI/CD to streamline workflows.
Next Steps:
Build personal projects to apply what you've learned
Contribute to open-source Python projects
Explore specialized libraries for your field (data science, web development, etc.)
Stay updated with Python's evolving ecosystem
Join Python communities and attend meetups or conferences
Python continues to grow and evolve, with new features and libraries being developed
constantly. The skills you've gained from this guide will serve as a solid foundation for your
programming journey.
Remember: The best way to learn Python is to write Python code. Start small, build
incrementally, and don't be afraid to experiment. Happy coding!
---
Additional Resources
Official Documentation
Python Documentation: [Link]
PEP 8 Style Guide: [Link]
Learning Platforms
Real Python: [Link]
[Link] Tutorial: [Link]
Codecademy Python Course: [Link]
Books
"Python Crash Course" by Eric Matthes
"Automate the Boring Stuff with Python" by Al Sweigart
"Fluent Python" by Luciano Ramalho
"Effective Python" by Brett Slatkin
Communities
Python Discord: [Link]
r/learnpython on Reddit
Stack Overflow Python tag
Practice Platforms
LeetCode: [Link]
HackerRank: [Link]
Codewars: [Link]
---
This guide provides a comprehensive foundation for Python programming. Continue exploring,
building, and learning to master this powerful language.