1: Introduction to Python
🔥 What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum in 1991 and is widely used in web development, data science, artificial intelligence, and automation.
🔍 Features and Applications of Python
✅ Easy to Learn – Simple syntax similar to English ✅ Interpreted Language – Executes code line by line ✅ Object-Oriented – Supports classes and objects ✅ Dynamically Typed – No need to define data types explicitly ✅ Extensive Libraries – NumPy, Pandas, TensorFlow, etc.
📌 Applications:
- Web Development 🌐 (Django, Flask)
- Data Science 📊 (Pandas, NumPy, Matplotlib)
- AI & ML 🤖 (TensorFlow, Scikit-learn)
- Automation ♻ (Selenium, PyAutoGUI)
- Cybersecurity 🔒 (Scapy, Requests)
🔧 Installing Python and Setting up the Environment
- Download Python from python.org
- Install IDEs like PyCharm, VS Code, or Jupyter Notebook
Check installation using:
python --version
🌟 Writing and Running Python Scripts
- Interactive Mode: Type python in terminal and run commands directly.
Script Mode: Save code in a .py file and run:
python script.py
🔄 Python Syntax and Indentation
Python uses indentation (spaces or tabs) to define code blocks, unlike other languages that use curly braces {}.
if 5 > 2:
print("Five is greater than two!") # Indented block
2: Basics of Python
🛠️ Variables and Data Types
Variables store values and do not require explicit declaration of type.
name = "Alice" # String
age = 25 # Integer
height = 5.7 # Float
is_student = True # Boolean
🔒 Keywords and Identifiers
- Keywords: Reserved words in Python (e.g., if, else, while, return)
- Identifiers: Variable and function names (must start with a letter or _)
💬 Input and Output (print(), input())
name = input("Enter your name: ")
print("Hello,", name)
🌟 Type Conversion and Type Casting
Implicit Conversion: Python automatically converts types.
x = 5 y = 2.5 result = x + y # result will be float (7.5)
Explicit Conversion (Casting):
a = "100" b = int(a) # Converts string to integer print(b + 50) # Output: 150
📝 Practice Questions:
- Write a Python script to print "Hello, World!".
- Create a program that asks for user input and prints their name.
- Declare three variables of different data types and print their values.
- Convert an integer to a string and concatenate it with another string.
3: Control Flow Statements
🔀 Conditional Statements (if, if-else, elif)
Conditional statements are used to execute code based on conditions.
x = 10
if x > 0:
print("Positive number")
elif x == 0:
print("Zero")
else:
print("Negative number")
🛠 Looping Statements (for, while)
Loops are used to execute a block of code multiple times.
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
⏪ Loop Control Statements (break, continue, pass)
- break: Exits the loop early
- continue: Skips the current iteration
- pass: Does nothing (placeholder)
for i in range(5):
if i == 3:
break # Stops loop at 3
print(i)
4: Functions and Modules
🔧 Defining Functions (def)
Functions are reusable blocks of code.
def greet(name):
return "Hello, " + name
print(greet("Alice"))
💬 Arguments and Return Values
Functions can accept arguments and return values.
def add(a, b):
return a + b
print(add(5, 3))
🚀 Lambda Functions
Lambda functions are anonymous functions.
square = lambda x: x * x
print(square(4)) # Output: 16
📈 map(), filter(), and reduce() Functions
- map(): Applies function to all elements in an iterable.
- filter(): Filters elements based on condition.
- reduce(): Reduces iterable to a single value.
from functools import reduce
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
sum_numbers = reduce(lambda x, y: x + y, numbers)
🔄 Importing and Creating Modules
Importing Modules
import math print(math.sqrt(16))
Creating a Module (Save as my_module.py)
def greet(name): return "Hello, " + name
Then import it in another script:
import my_module print(my_module.greet("Alice"))
✨ 5: Data Structures in Python
📂 Lists
Lists are ordered, mutable (changeable) collections in Python.
Declaration:
my_list = [1, 2, 3, "hello", 4.5]
Operations:
my_list.append(6) # Adds 6 to the list
my_list.remove(2) # Removes 2 from the list
print(len(my_list)) # Returns length of list
Slicing:
print(my_list[1:4]) # Extracts elements from index 1 to 3
List Comprehension:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Practice Question:
✅ Create a list of first 10 even numbers using list comprehension.
📃 Tuples
Tuples are ordered, immutable (unchangeable) collections.
Properties:
- Immutable: Cannot change elements after creation.
- Faster than lists.
- Can be used as dictionary keys.
Tuple Operations:
tuple1 = (1, 2, 3, "Python")
print(tuple1[2]) # Access element at index 2
print(len(tuple1)) # Returns tuple length
Practice Question:
✅ What happens when you try to modify a tuple?
🎲 Sets
Sets are unordered collections with unique elements.
Properties:
- No duplicate elements.
- Unordered.
- Supports set operations (union, intersection, etc.).
Set Operations:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # Union
print(set1 & set2) # Intersection
Practice Question:
✅ Create a set with unique characters from a string "banana".
📒 Dictionaries
Dictionaries store key-value pairs.
Keys & Values:
dict1 = {"name": "Alice", "age": 25, "city": "NYC"}
print(dict1["name"]) # Access value using key
Dictionary Methods:
dict1.update({"age": 26}) # Updates value
dict1.pop("city") # Removes key-value pair
print(dict1.keys()) # Returns all keys
Practice Question:
✅ Create a dictionary where keys are numbers from 1 to 5 and values are their squares.
🌟 6: String Handling
🌐 String Basics & Operations
s = "Hello, Python!"
print(s[0]) # Access first character
print(s.upper()) # Convert to uppercase
📚 String Formatting
name = "John"
age = 25
print("My name is {} and I am {} years old".format(name, age)) # Using format()
print(f"My name is {name} and I am {age} years old") # Using f-strings
⚙️ String Methods
s = "Hello World"
print(s.split()) # ['Hello', 'World']
print("-".join(["Python", "is", "fun"])) # Python-is-fun
print(s.replace("Hello", "Hi")) # Hi World
📝 Regular Expressions (re module)
import re
text = "My number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
print(match.group()) # Output: 123-456-7890
Practice Question:
✅ Write a regex pattern to find all email addresses in a string.
7: File Handling 📁
Python provides efficient ways to handle files, allowing you to perform operations like opening, reading, writing, and appending data. Understanding file handling is crucial for tasks such as data storage and retrieval.
File Open, Read, Write, and Append
Opening a File: Use the open() function to open a file. It returns a file object and takes two parameters: the filename and the mode.
file = open('example.txt', 'r') # 'r' mode opens the file for reading
Reading a File: After opening a file in read mode, you can read its content using methods like read(), readline(), or readlines().
content = file.read() # Reads the entire content of the file print(content)
Writing to a File: To write data, open the file in write ('w') or append ('a') mode.
file = open('example.txt', 'w') # 'w' mode opens the file for writing file.write('Hello, World!')
Appending to a File: Use append mode to add data to the end of the file without overwriting existing content.
file = open('example.txt', 'a') # 'a' mode opens the file for appending file.write('\nAppended text.')
Closing a File: Always close the file after completing operations to free up system resources.
file.close()
Working with Text and Binary Files
Text Files: These files contain human-readable characters. Open them in text mode ('t'), which is the default.
file = open('example.txt', 'rt') # 'r' for read, 't' for text mode
Binary Files: These files contain binary data (e.g., images, videos). Open them in binary mode ('b').
file = open('example.jpg', 'rb') # 'r' for read, 'b' for binary mode
Exception Handling in File Operations
To handle potential errors during file operations, use try-except blocks.
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError:
print('File not found.')
finally:
file.close()
Using the with statement ensures the file is properly closed, even if an error occurs.
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print('File not found.')
8: Exception Handling 🚫
Exceptions are errors that occur during program execution. Proper handling ensures your program can manage errors gracefully without crashing.
Types of Errors in Python
Syntax Errors: Occur due to incorrect syntax. Detected during parsing.
if True print('Hello') # Missing colon (:) results in a syntax error
Exceptions: Errors detected during execution (e.g., ZeroDivisionError, FileNotFoundError).
result = 10 / 0 # Raises ZeroDivisionError
try, except, finally Blocks
try Block: Contains code that might raise an exception.
except Block: Handles the exception if one occurs.
finally Block: Executes code regardless of whether an exception occurred or not.
try: file = open('example.txt', 'r') content = file.read() except FileNotFoundError: print('File not found.') finally: file.close()
Handling Multiple Exceptions
You can handle different exceptions separately.
try:
value = int(input('Enter a number: '))
result = 10 / value
except ValueError:
print('Invalid input. Please enter a number.')
except ZeroDivisionError:
print('Cannot divide by zero.')
Raising Exceptions (raise)
Use the raise statement to trigger an exception manually.
def check_age(age):
if age < 0:
raise ValueError('Age cannot be negative.')
return age
try:
user_age = check_age(-1)
except ValueError as e:
print(e)
By mastering file handling and exception management, you can build robust and error-resistant Python applications.
9: Object-Oriented Programming (OOP) in Python 🚀
Object-Oriented Programming (OOP) is a paradigm that organizes code into classes and objects, making it reusable, modular, and easier to understand. Let's dive into its key concepts with examples! 🐍
Classes and Objects 🏛️
- Class: A blueprint for creating objects.
- Object: An instance of a class with attributes (data) and methods (functions).
# Example: Class and Object
class Parrot:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating objects
parrot1 = Parrot("Blu", 10)
parrot2 = Parrot("Woo", 15)
print(f"{parrot1.name} is {parrot1.age} years old.") # Output: Blu is 10 years old.
print(f"{parrot2.name} is {parrot2.age} years old.") # Output: Woo is 15 years old.
🖼️ Visualize: Think of a class as a cookie cutter and objects as cookies 🍪.
Constructors (__init__ Method) 🛠️
- The __init__ method initializes the attributes of an object when it's created.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Tesla", "Model S")
print(f"Car: {car1.brand}, Model: {car1.model}") # Output: Car: Tesla, Model: Model S
Instance and Class Variables 📂
- Instance Variables: Unique to each object.
- Class Variables: Shared across all instances of the class.
class Dog:
species = "Canis lupus" # Class variable
def __init__(self, name):
self.name = name # Instance variable
dog1 = Dog("Buddy")
dog2 = Dog("Charlie")
print(dog1.species) # Output: Canis lupus (shared)
print(dog2.name) # Output: Charlie (unique)
Inheritance and Method Overriding 🧬
- Inheritance allows a child class to inherit attributes and methods from a parent class.
- Method Overriding lets the child class redefine methods from the parent class.
class Animal:
def speak(self):
print("I make sounds.")
class Dog(Animal):
def speak(self): # Overriding method
print("Woof! Woof!")
dog = Dog()
dog.speak() # Output: Woof! Woof!
Polymorphism and Encapsulation 🎭🔒
- Polymorphism: Methods can have different implementations depending on the object.
- Encapsulation: Restricts access to certain attributes/methods using _ or __.
# Polymorphism Example
class Bird:
def fly(self):
print("I can fly.")
class Penguin(Bird):
def fly(self): # Overriding to provide specific behavior
print("I cannot fly.")
bird = Bird()
penguin = Penguin()
bird.fly() # Output: I can fly.
penguin.fly() # Output: I cannot fly.
# Encapsulation Example
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # Output: 1000
10: Python Standard Library and Modules 📚
Python's standard library provides built-in modules to perform various tasks efficiently. Let's explore some key modules. 🌟
os Module (Files and Directories) 📁
Used for interacting with the operating system.
import os
# Get current directory
print(os.getcwd())
# Create a directory
os.mkdir("new_folder")
# List files in a directory
print(os.listdir())
sys Module (Command Line Arguments) 💻
Used for interacting with the Python interpreter.
import sys
# Print command-line arguments
print(sys.argv)
# Exit the program
sys.exit()
Run the script with arguments like:
python script.py arg1 arg2
Output:
['script.py', 'arg1', 'arg2']
math Module (Mathematical Operations) ➗✔️
Provides mathematical functions.
import math
print(math.sqrt(16)) # Square root (Output: 4.0)
print(math.pi) # Value of π (Output: 3.141592653589793)
print(math.factorial(5)) # Factorial (Output: 120)
datetime Module (Date and Time) ⏰📅
Used for working with dates and times.
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
print(now)
# Adding days to current date
future_date = now + timedelta(days=7)
print(future_date)
# Formatting date/time output
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
11: Python with Databases (MySQL, SQLite) 📊
Databases are essential for storing and managing data efficiently. Python supports various databases, including MySQL and SQLite. This guide will walk you through how to interact with these databases using Python.
Introduction to Databases 📚
- Database: A structured collection of data.
- SQL (Structured Query Language): A language for managing relational databases.
- MySQL: A widely used open-source relational database management system.
- SQLite: A lightweight, self-contained database engine that requires no server.
Connecting Python with MySQL and SQLite 🌐
Connecting to SQLite 📁
Python's standard library includes the sqlite3 module for SQLite connectivity.
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('example.db')
print("Connected to SQLite Database")
# Close the connection
conn.close()
Connecting to MySQL 📊
You need to install a MySQL driver like mysql-connector-python.
import mysql.connector
# Install MySQL Connector using pip
# pip install mysql-connector-python
# Connect to MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
print("Connected to MySQL Database")
# Close the connection
mydb.close()
Performing CRUD Operations 📝
CRUD stands for Create, Read, Update, Delete operations.
Create 📈
SQLite Example:
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() # Create table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') # Insert data cursor.execute("INSERT INTO users (name, age) VALUES ('John Doe', 30)") conn.commit() conn.close()
MySQL Example:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) cursor = mydb.cursor() # Create table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT ) ''') # Insert data cursor.execute("INSERT INTO users (name, age) VALUES ('John Doe', 30)") mydb.commit() mydb.close()
Read 📊
SQLite Example:
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row) conn.close()
MySQL Example:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) cursor = mydb.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row) mydb.close()
Update 🔄
SQLite Example:
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() cursor.execute("UPDATE users SET age = 31 WHERE name = 'John Doe'") conn.commit() conn.close()
MySQL Example:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) cursor = mydb.cursor() cursor.execute("UPDATE users SET age = 31 WHERE name = 'John Doe'") mydb.commit() mydb.close()
Delete 🗑️
SQLite Example:
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() cursor.execute("DELETE FROM users WHERE name = 'John Doe'") conn.commit() conn.close()
MySQL Example:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) cursor = mydb.cursor() cursor.execute("DELETE FROM users WHERE name = 'John Doe'") mydb.commit() mydb.close()
12: Multithreading and Concurrency 🌈
Multithreading allows a program to execute multiple threads concurrently, improving responsiveness and efficiency.
Introduction to Threads in Python 🧕
- Thread: A separate flow of execution within a program.
- Threading Module: Python's built-in module for creating threads.
Using the threading Module 📚
import threading
import time
def print_numbers():
for i in range(10):
time.sleep(1)
print(i)
def print_letters():
for letter in 'abcdefghij':
time.sleep(1)
print(letter)
# Create threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Start threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
Synchronization and Race Conditions 🔒
- Synchronization: Ensures only one thread accesses shared resources at a time.
- Race Conditions: Occur when multiple threads access shared data simultaneously.
import threading
class Counter:
def __init__(self):
self.count = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.count += 1
counter = Counter()
def worker():
for _ in range(100000):
counter.increment()
threads = []
for _ in range(10):
thread = threading.Thread(target=worker)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print(counter.count) # Expected output: 1000000
13: Python Libraries and Frameworks 📚🐍
Python offers a wide range of libraries and frameworks to simplify development in various domains, including numerical computing, data manipulation, visualization, and machine learning.
NumPy (for Numerical Computing) 💢
- Purpose: Efficient handling of numerical data and mathematical operations.
- Key Features:
- Multi-dimensional arrays (ndarray).
- Mathematical functions (e.g., mean, dot, sum).
- Broadcasting for element-wise operations.
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4])
# Perform operations
print(np.mean(arr)) # Output: 2.5
print(arr * 2) # Output: [2 4 6 8]
Pandas (for Data Manipulation) 🐼
- Purpose: Data analysis and manipulation using DataFrames.
- Key Features:
- Handling missing data.
- Filtering, grouping, and merging datasets.
import pandas as pd
# Create a DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
# Access data
print(df['Name']) # Output: Alice, Bob
print(df[df['Age'] > 26]) # Filter rows where Age > 26
Matplotlib & Seaborn (for Data Visualization) 📊🎨
Matplotlib
- Purpose: Basic plotting library.
- Key Features:
- Line plots, bar charts, scatter plots.
import matplotlib.pyplot as plt
# Line plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Line Plot")
plt.show()
Seaborn
- Purpose: High-level interface for statistical plots.
- Key Features:
- Heatmaps, pair plots, distribution plots.
import seaborn as sns
# Distribution plot
sns.histplot([1, 2, 2, 3], kde=True)
plt.show()
Scikit-learn (for Machine Learning) 🤖
- Purpose: Tools for building machine learning models.
- Key Features:
- Preprocessing data.
- Classification, regression, clustering algorithms.
from sklearn.linear_model import LinearRegression
# Simple linear regression
model = LinearRegression()
X = [[1], [2], [3]]
y = [2, 4, 6]
model.fit(X, y)
print(model.predict([[4]])) # Output: [8.]
14: Web Development with Python 🌐💻
Python frameworks like Flask and Django make web development efficient by providing tools for building scalable applications.
Introduction to Flask and Django
Flask 🧪 (Microframework)
- Lightweight and minimalistic.
- Suitable for small projects or APIs.
Django 🏰️ (Full-stack Framework)
- Feature-rich with built-in tools for authentication, ORM, and admin interface.
- Suitable for large-scale applications.
Creating a Simple Web Application
Using Flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Run the script and visit http://127.0.0.1:5000/.
Using Django:
- Install Django: pip install django.
Create a project:
django-admin startproject mysite cd mysite python manage.py runserver
Visit http://127.0.0.1:8000/.
REST APIs in Python
Using Flask:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({'key': 'value'})
if __name__ == '__main__':
app.run(debug=True)
Test the API with tools like Postman or curl.
15: Introduction to Data Science and Machine Learning 📈🤖
Data Science involves extracting insights from data using statistical methods and machine learning techniques.
Basics of Data Science
- Data Collection: Gathering raw data from various sources.
- Data Cleaning: Handling missing values or outliers.
- Analysis & Visualization: Using libraries like Pandas and Matplotlib.
Introduction to Machine Learning
- Machine Learning enables systems to learn patterns from data without explicit programming.
- Types of ML:
- Supervised Learning (e.g., Regression).
- Unsupervised Learning (e.g., Clustering).
Building a Simple ML Model with Scikit-learn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Load dataset
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# Train model
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
# Predict on test data
predictions = model.predict(X_test)
print(predictions)