Python Cheat Sheet
All essential Python syntax and examples in one place
For Detailed Documentation Or Video Lecture Visit Here
1. Basics
Print
print("Hello World")
Comments
# Single line comment '''This is a multi-line comment'''
Variables
x = 5 y = "Hello"
Data Types
int # Integer
float # Decimal
str # String
list # [1,2,3]
tuple # (1,2,3)
dict # {"key": "value"}
set # {1,2,3}
bool # True / False
Type Casting
int("5") # Convert string to int
str(5) # Convert int to string
float("3.14")# Convert string to float
2. Operators
Arithmetic Operators
+ Addition (5 + 3 = 8) - Subtraction (5 - 3 = 2) * Multiplication (5 * 3 = 15) / Division (5 / 2 = 2.5) // Floor Division (5 // 2 = 2) % Modulus (5 % 2 = 1) ** Exponentiation (2 ** 3 = 8)
Comparison Operators
== Equal != Not equal > Greater than < Less than >= Greater or equal <= Less or equal
Logical Operators
and Returns True if both are true or Returns True if one is true not Reverses the result
Membership Operators
x in list # True if x exists in list x not in list # True if x does not exist
Identity Operators
x is y # True if same object x is not y # True if not same object
3. Control Flow
If-Else Statements
x = 10
if x > 5:
print("Greater than 5")
elif x == 5:
print("Equal to 5")
else:
print("Less than 5")
For Loop
for i in range(5):
print(i)
While Loop
count = 0
while count < 5:
print(count)
count += 1
Loop Control
for i in range(5):
if i == 3:
continue # Skips 3
if i == 4:
break # Stops loop
print(i)
4. Functions
Defining a Function
def greet():
print("Hello, World!")
Function with Parameters
def add(a, b):
return a + b
print(add(3, 5))
Default Arguments
def greet(name="User"):
print("Hello", name)
*args and **kwargs
def example(*args, **kwargs):
print(args)
print(kwargs)
example(1,2,3, name="Aditya", age=16)
Lambda Functions
square = lambda x: x**2 print(square(5))
Scope
x = 10
def func():
global x
x = 20
5. Data Structures
Strings
s = "Python" print(s.upper()) # "PYTHON" print(s.lower()) # "python" print(s[0:3]) # "Pyt"
Lists
mylist = [1, 2, 3] mylist.append(4) # [1, 2, 3, 4] mylist.remove(2) # [1, 3, 4] print(mylist[0]) # 1
Tuples
mytuple = (1, 2, 3) print(mytuple[1]) # 2
Dictionaries
mydict = {"name": "Aditya", "age": 16}
print(mydict["name"]) # Aditya
mydict["age"] = 17
Sets
myset = {1, 2, 3}
myset.add(4) # {1, 2, 3, 4}
myset.remove(2) # {1, 3, 4}
6. File Handling
Read a File
with open("file.txt", "r") as f:
data = f.read()
print(data)
Write to a File
with open("file.txt", "w") as f:
f.write("Hello, World!")
Append to a File
with open("file.txt", "a") as f:
f.write("\\nNew Line")
Read Lines
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
Working with JSON
import json
data = {"name": "Aditya", "age": 16}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
print(json.load(f))
7. Error & Exception Handling
Basic Try-Except
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Try-Except-Else
try:
x = 5 / 1
except:
print("Error occurred")
else:
print("No error, result:", x)
Try-Except-Finally
try:
f = open("file.txt")
except FileNotFoundError:
print("File not found")
finally:
print("This will always run")
Raise an Exception
x = -1
if x < 0:
raise ValueError("Negative value not allowed")
8. Modules & Packages
Importing Modules
import math print(math.sqrt(16))
From Import
from random import randint print(randint(1, 10))
Alias Import
import numpy as np arr = np.array([1, 2, 3])
Built-in Modules
import os print(os.getcwd()) import datetime print(datetime.datetime.now())
Installing Packages
# Install with pip
pip install requests
# Use installed package
import requests
res = requests.get("https://example.com")
print(res.status_code)
Create Your Own Module
# mymodule.py
def greet(name):
return f"Hello {name}"
# main.py
import mymodule
print(mymodule.greet("Aditya"))
9. Object-Oriented Programming (OOP)
Basic Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Aditya", 16)
print(p1.name)
Instance & Class Methods
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
def instance_method(self):
return "Instance method"
@classmethod
def class_method(cls):
return f"Objects created: {cls.count}"
@staticmethod
def static_method():
return "Static method"
Inheritance
class Animal:
def speak(self):
print("I am an animal")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
d.speak()
Polymorphism
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Woof"
for animal in (Cat(), Dog()):
print(animal.sound())
Magic Methods
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
b = Book("Python 101")
print(b)
10. Advanced Python
List Comprehension
squares = [x**2 for x in range(5)] print(squares)
Generator
def gen():
for i in range(3):
yield i
for val in gen():
print(val)
Decorators
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def say_hello():
print("Hello")
say_hello()
Context Managers
with open("file.txt", "w") as f:
f.write("Hello World")
Regular Expressions
import re text = "My number is 12345" result = re.findall(r"\d+", text) print(result) # ['12345']
Virtual Environments
# Create venv python -m venv myenv # Activate (Windows) myenv\Scripts\activate # Activate (Linux/Mac) source myenv/bin/activate
11. Python for Automation
System Commands
import os
os.system("echo Hello World")
Subprocess
import subprocess result = subprocess.run(["ls", "-l"], capture_output=True, text=True) print(result.stdout)
Working with Excel
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws["A1"] = "Hello Excel"
wb.save("sample.xlsx")
Working with PDFs
from PyPDF2 import PdfReader
reader = PdfReader("file.pdf")
print(reader.pages[0].extract_text())
Web Scraping
import requests
from bs4 import BeautifulSoup
res = requests.get("https://example.com")
soup = BeautifulSoup(res.text, "html.parser")
print(soup.title.text)
APIs & JSON
import requests
res = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(res.json())
12. Python for Web Development
Flask Example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)
Django Example (Overview)
# Install Django pip install django # Start project django-admin startproject myproject # Run server python manage.py runserver
Simple REST API with Flask
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api")
def api():
return jsonify({"message": "Hello API"})
if __name__ == "__main__":
app.run()
13. Data Handling
NumPy Basics
import numpy as np arr = np.array([1, 2, 3]) print(arr.mean())
Pandas Basics
import pandas as pd
data = {"name": ["Aditya", "Raj"], "age": [16, 18]}
df = pd.DataFrame(data)
print(df.head())
Matplotlib
import matplotlib.pyplot as plt x = [1,2,3] y = [2,4,6] plt.plot(x, y) plt.show()
14. Python for Cybersecurity
Hashing (MD5, SHA256)
import hashlib print(hashlib.md5(b"password").hexdigest()) print(hashlib.sha256(b"password").hexdigest())
Port Scanner
import socket
for port in range(20, 25):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if s.connect_ex(("127.0.0.1", port)) == 0:
print(f"Port {port} open")
s.close()
Brute Force Simulation
import itertools
chars = "abc123"
for attempt in itertools.product(chars, repeat=3):
print("".join(attempt))
Automating Nmap
import os
os.system("nmap -sV 127.0.0.1")
15. Testing & Debugging
Debugging with pdb
import pdb x = 5 pdb.set_trace() print(x * 2)
Unit Testing
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_sum(self):
self.assertEqual(add(2, 3), 5)
unittest.main()
Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")