Python Handbook — From Zero to Hero
Table of Contents
1. Python Basics
Variables and Data Types
# Variables
name = "Vaibhav"
age = 25
height = 5.9
is_student = True
# Data Types
print(type(name)) # str
print(type(age)) # int
print(type(height)) # float
print(type(is_student)) # bool
Strings
# String Operations
name = "DSWallah"
print(name.upper()) # DSWALLAH
print(name.lower()) # dswallah
print(name.replace("D", "X")) # XSWallah
print(name[0:3]) # DSW
print(len(name)) # 8
# f-strings (formatted strings)
name = "Vaibhav"
age = 25
print(f"Hello, I am {name} and I am {age} years old")
Conditional Statements
# if-elif-else
age = 25
if age < 18:
print("Minor")
elif age < 60:
print("Adult")
else:
print("Senior")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"
Loops
# for loop
for i in range(10):
print(i)
# while loop
count = 0
while count < 5:
print(count)
count += 1
# List comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2. Data Structures
Lists
# Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add to end
fruits.insert(1, "mango") # Insert at index 1
fruits.remove("banana") # Remove specific item
fruits.pop() # Remove last item
print(fruits[0]) # Access by index
print(len(fruits)) # Length
Dictionaries
# Dictionaries
student = {
"name": "Vaibhav",
"age": 25,
"course": "Data Science"
}
print(student["name"]) # Access value
student["email"] = "vaibhav@dswallah.com" # Add new key
del student["age"] # Delete key
print(student.keys()) # All keys
print(student.values()) # All values
Sets and Tuples
# Sets (unique elements)
colors = {"red", "blue", "green", "red"}
print(colors) # {'red', 'blue', 'green'}
# Tuples (immutable)
point = (10, 20)
print(point[0]) # 10
3. Object-Oriented Programming
# Classes and Objects
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I am {self.name} and I am {self.age} years old"
# Create object
student1 = Student("Vaibhav", 25)
print(student1.introduce())
4. NumPy
import numpy as np
# Arrays
arr = np.array([1, 2, 3, 4, 5])
print(arr.mean()) # 3.0
print(arr.std()) # 1.4142135623730951
print(arr.max()) # 5
# 2D Arrays
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape) # (2, 3)
print(matrix.T) # Transpose
5. Pandas
import pandas as pd
# DataFrame
data = {
"Name": ["Vaibhav", "Rahul", "Priya"],
"Age": [25, 30, 28],
"Course": ["Data Science", "AI", "ML"]
}
df = pd.DataFrame(data)
# Operations
print(df.head()) # First 5 rows
print(df.describe()) # Statistics
print(df[df["Age"] > 25]) # Filter
print(df.groupby("Course").mean()) # Group by
6. Matplotlib
import matplotlib.pyplot as plt
# Line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Line Plot")
plt.show()
# Bar chart
plt.bar(["A", "B", "C"], [10, 20, 15])
plt.show()
7. Web Scraping
import requests
from bs4 import BeautifulSoup
# Fetch webpage
url = "https://example.com"
response = requests.get(url)
# Parse HTML
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("h2")
for title in titles:
print(title.text)
8. Automation
# Email automation
import smtplib
def send_email(to, subject, body):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login("your-email@gmail.com", "your-password")
message = f"Subject: {subject}
{body}"
server.sendmail("your-email@gmail.com", to, message)
server.quit()
# File automation
import os
import shutil
# Organize files by extension
for file in os.listdir("downloads"):
if file.endswith(".pdf"):
shutil.move(f"downloads/{file}", "pdfs/")
elif file.endswith(".jpg"):
shutil.move(f"downloads/{file}", "images/")
9. Python Projects for Resume
Web Scraper
Scrape data from websites using BeautifulSoup and requests
Automation Scripts
Email automation, file organization, data entry
Data Analysis
Analyze datasets using Pandas and Matplotlib
API Development
Build REST APIs using FastAPI or Flask
Chatbot
Build a chatbot using NLP libraries
10. Python Interview Questions
Q: What is the difference between list and tuple?
A: Lists are mutable (can modify), tuples are immutable (cannot modify). Tuples are faster and use less memory.
Q: What is a decorator?
A: A decorator is a function that adds functionality to another function without modifying it. Use @decorator syntax.
Q: What is the difference between == and is?
A: == checks value equality, is checks identity (same object in memory).
Download Python Handbook PDF
Get the complete Python Handbook as a free PDF. Enter your email to receive the download link.
Start Learning with DSWallah
Join 300+ students who transformed their careers with DSWallah. IIT-certified mentor, 50+ real projects, placement support.
WhatsApp for Free Demo →