Python Programming

Complete Python cheatsheet

Complete Python Programming Cheatsheet

1. Introduction to Python

Python is a high-level, interpreted, general-purpose programming language known for its simple syntax and readability.

Features

Applications

Check Python Version

python --version python3 --version

Run a Python File

python main.py

2. Python Program Structure

First Python Program

print("Hello, World!")

Comments

# Single-line comment """ Multi-line string often used as a comment. """ ''' Another multi-line string. '''

Print Multiple Values

print("Python", "Programming") print("Hello", "World", sep="-") print("Hello", end=" ") print("Python")

Docstrings

def greet(): """Display a greeting message.""" print("Hello!") print(greet.__doc__)

3. Python Variables

Variables store data values.

name = "Uday" age = 22 height = 5.8 is_student = True

Multiple Assignment

a, b, c = 10, 20, 30 x = y = z = 100

Variable Naming Rules

user_name = "Alex" total_marks = 450 _private = 100

Naming Conventions

TypeConventionExample
Variablesnake_caseuser_name
Functionsnake_casecalculate_total()
ClassPascalCaseStudentRecord
ConstantUPPER_CASEMAX_SIZE
Private conventionLeading underscore_value

Check Variable Type

x = 100 print(type(x))

Delete a Variable

x = 10 del x

4. Python Data Types

Python has several built-in data types.

CategoryData TypeExample
Numericint100
Numericfloat10.5
Numericcomplex2 + 3j
BooleanboolTrue
Textstr"Python"
Sequencelist[1, 2, 3]
Sequencetuple(1, 2, 3)
Sequencerangerange(5)
Mappingdict{"name": "Alex"}
Setset{1, 2, 3}
Setfrozensetfrozenset({1, 2})
Binarybytesb"Hello"
Binarybytearraybytearray(5)
Binarymemoryviewmemoryview(bytes(5))
NoneNoneTypeNone

Numeric Types

a = 10 b = 10.5 c = 2 + 3j print(type(a)) print(type(b)) print(type(c))

Boolean

is_active = True is_logged_in = False print(10 > 5) # True

Type Conversion

x = "100" a = int(x) b = float(x) c = str(100) d = bool(1) print(a, b, c, d)

Type Checking

x = 10 print(type(x)) print(isinstance(x, int))

5. Input and Output

Taking User Input

name = input("Enter your name: ") print("Hello", name)

Integer Input

age = int(input("Enter your age: ")) print(age)

Float Input

price = float(input("Enter price: "))

Multiple Inputs

a, b = input("Enter two values: ").split() x, y = map(int, input("Enter numbers: ").split())

Formatted Output

name = "Alex" age = 20 print("Name:", name) print("Age:", age) print(f"My name is {name} and I am {age} years old.") print("Age: {}".format(age)) print("Name: %s" % name)

Number Formatting

price = 1234.5678 print(f"{price:.2f}") print(f"{price:,.2f}") print(f"{0.25:.1%}")

6. Python Operators

Arithmetic Operators

OperatorDescriptionExample
+Addition10 + 5
-Subtraction10 - 5
*Multiplication10 * 5
/Division10 / 5
//Floor division10 // 3
%Modulus10 % 3
**Exponentiation2 ** 3
a = 10 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print(a ** b)

Comparison Operators

OperatorMeaning
==Equal
!=Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
a = 10 b = 20 print(a == b) print(a != b) print(a > b) print(a < b)

Logical Operators

OperatorDescription
andTrue if both conditions are true
orTrue if at least one condition is true
notReverses the Boolean result
age = 22 print(age > 18 and age < 60) print(age < 18 or age > 60) print(not age > 18)

Assignment Operators

x = 10 x += 5 x -= 2 x *= 2 x /= 2 x //= 2 x %= 3 x **= 2

Bitwise Operators

OperatorDescription
&AND
|OR
^XOR
~NOT
<<Left shift
>>Right shift
a = 10 b = 5 print(a & b) print(a | b) print(a ^ b) print(~a) print(a << 1) print(a >> 1)

Membership Operators

languages = ["Python", "Java", "C++"] print("Python" in languages) print("PHP" not in languages)

Identity Operators

a = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) print(a is c) print(a == c) print(a is not c)

== compares values, while is checks object identity.

7. Conditional Statements

if Statement

age = 20 if age >= 18: print("Eligible to vote")

if-else Statement

number = 10 if number % 2 == 0: print("Even") else: print("Odd")

if-elif-else Statement

marks = 85 if marks >= 90: print("Grade A+") elif marks >= 80: print("Grade A") elif marks >= 70: print("Grade B") else: print("Grade C")

Nested if

age = 22 has_id = True if age >= 18: if has_id: print("Access granted")

Conditional Expression

age = 20 status = "Adult" if age >= 18 else "Minor" print(status)

match-case (Python 3.10+)

day = 2 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case _: print("Invalid day")

8. Loops

for Loop

for i in range(5): print(i)

range()

range(stop) range(start, stop) range(start, stop, step)

Examples:

for i in range(1, 6): print(i) for i in range(2, 11, 2): print(i) for i in range(10, 0, -1): print(i)

while Loop

count = 1 while count <= 5: print(count) count += 1

break

for i in range(10): if i == 5: break print(i)

continue

for i in range(5): if i == 2: continue print(i)

pass

for i in range(5): pass

else with Loops

for i in range(3): print(i) else: print("Loop completed")

The loop's else block executes when the loop finishes normally, not when it exits through break.

Nested Loops

for i in range(1, 4): for j in range(1, 4): print(i, j)

9. Strings

Strings are immutable sequences of Unicode characters.

text = "Python Programming"

String Indexing

text = "Python" print(text[0]) print(text[1]) print(text[-1]) print(text[-2])

String Slicing

text = "Programming" print(text[0:4]) print(text[2:7]) print(text[:5]) print(text[5:]) print(text[::-1])

Syntax:

string[start:stop:step]

String Methods

text = " hello python " print(text.upper()) print(text.lower()) print(text.title()) print(text.capitalize()) print(text.strip()) print(text.lstrip()) print(text.rstrip()) print(text.replace("python", "world")) print(text.split()) print(text.count("o")) print(text.find("python")) print(text.index("python")) print(text.startswith("hello")) print(text.endswith("python"))

String Testing Methods

text = "Python123" print(text.isalpha()) print(text.isdigit()) print(text.isalnum()) print(text.islower()) print(text.isupper()) print(text.isspace()) print(text.istitle())

String Concatenation

first = "Hello" second = "World" result = first + " " + second print(result)

String Repetition

print("Python " * 3)

String Formatting

name = "Alex" age = 20 print(f"{name} is {age} years old.") print("{} is {} years old.".format(name, age))

Multiline Strings

message = """ Welcome to Python. Learn programming. Build projects. """

10. Lists

Lists are ordered, mutable collections that allow duplicate values.

numbers = [10, 20, 30, 40]

Access List Elements

print(numbers[0]) print(numbers[-1])

Modify Elements

numbers[0] = 100

List Methods

items = [10, 20, 30] items.append(40) items.extend([50, 60]) items.insert(1, 15) items.remove(20) items.pop() items.pop(0) items.sort() items.reverse() print(items) print(items.index(30)) print(items.count(10))

Copy a List

a = [1, 2, 3] b = a.copy() c = a[:]

List Slicing

numbers = [10, 20, 30, 40, 50] print(numbers[1:4]) print(numbers[:3]) print(numbers[2:]) print(numbers[::-1])

List Comprehension

squares = [x ** 2 for x in range(1, 6)] even = [x for x in range(10) if x % 2 == 0] print(squares) print(even)

Nested Lists

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[0][1])

Useful Built-in Functions

numbers = [10, 20, 30, 40] print(len(numbers)) print(max(numbers)) print(min(numbers)) print(sum(numbers)) print(sorted(numbers))

11. Tuples

Tuples are ordered and immutable collections.

numbers = (10, 20, 30)

Access Elements

print(numbers[0]) print(numbers[-1])

Single-Element Tuple

single = (10,)

Tuple Methods

values = (10, 20, 10, 30) print(values.count(10)) print(values.index(20))

Tuple Packing and Unpacking

student = ("Alex", 20, "CSE") name, age, course = student print(name) print(age) print(course)

Convert Between List and Tuple

numbers = [1, 2, 3] t = tuple(numbers) l = list(t)

12. Sets

Sets are unordered collections of unique elements.

numbers = {1, 2, 3, 4}

Create an Empty Set

empty_set = set()

Set Methods

numbers = {1, 2, 3} numbers.add(4) numbers.update([5, 6]) numbers.remove(2) numbers.discard(10) numbers.pop() numbers.clear()

remove() raises KeyError if the element is missing, while discard() does not.

Set Operations

a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # Union print(a & b) # Intersection print(a - b) # Difference print(a ^ b) # Symmetric difference

Set Relationships

a = {1, 2} b = {1, 2, 3} print(a.issubset(b)) print(b.issuperset(a)) print(a.isdisjoint({4, 5}))

Frozenset

values = frozenset([1, 2, 3])

A frozenset is immutable.

13. Dictionaries

Dictionaries store data in key-value pairs.

student = { "name": "Alex", "age": 20, "course": "CSE" }

Access Values

print(student["name"]) print(student.get("age")) print(student.get("marks", 0))

Add and Update Values

student["marks"] = 90 student["age"] = 21 student.update({"city": "Delhi"})

Remove Elements

student.pop("age") student.popitem() del student["name"]

Dictionary Methods

print(student.keys()) print(student.values()) print(student.items()) print(student.copy())

Loop Through Dictionary

student = { "name": "Alex", "age": 20 } for key in student: print(key) for value in student.values(): print(value) for key, value in student.items(): print(key, value)

Dictionary Comprehension

squares = {x: x ** 2 for x in range(1, 6)} print(squares)

Nested Dictionary

students = { "student1": { "name": "Alex", "age": 20 }, "student2": { "name": "John", "age": 21 } } print(students["student1"]["name"])

14. Functions

Functions are reusable blocks of code.

Define a Function

def greet(): print("Hello Python") greet()

Function with Parameters

def greet(name): print("Hello", name) greet("Alex")

Return Statement

def add(a, b): return a + b result = add(10, 20) print(result)

Default Arguments

def greet(name="Guest"): print("Hello", name) greet() greet("Alex")

Keyword Arguments

def student(name, age): print(name, age) student(age=20, name="Alex")

Arbitrary Positional Arguments

def total(*numbers): return sum(numbers) print(total(10, 20, 30))

Arbitrary Keyword Arguments

def details(**data): print(data) details(name="Alex", age=20, course="CSE")

Positional-Only and Keyword-Only Parameters

def calculate(a, b, /, *, operation): print(a, b, operation) calculate(10, 20, operation="add")

Parameters before / are positional-only. Parameters after * are keyword-only.

Lambda Functions

square = lambda x: x ** 2 print(square(5))

Recursive Function

def factorial(n): if n == 0: return 1 return n * factorial(n - 1) print(factorial(5))

Function Annotations

def add(a: int, b: int) -> int: return a + b

Annotations do not enforce types at runtime by themselves.

15. Scope of Variables

Python uses the LEGB rule:

  1. Local
  2. Enclosing
  3. Global
  4. Built-in

Local Variable

def show(): x = 10 print(x) show()

Global Variable

x = 100 def display(): print(x) display()

global Keyword

count = 0 def update(): global count count += 1 update()

nonlocal Keyword

def outer(): x = 10 def inner(): nonlocal x x = 20 inner() print(x) outer()

16. Modules and Packages

A module is a Python file containing reusable code. A package organizes modules.

Import a Module

import math print(math.sqrt(25))

Import Specific Functions

from math import sqrt, pi print(sqrt(16)) print(pi)

Alias

import math as m print(m.factorial(5))

Common Standard Library Modules

ModulePurpose
mathMathematical functions
randomRandom numbers
osOperating system operations
sysPython interpreter utilities
pathlibFile paths
datetimeDate and time
timeTime-related functions
reRegular expressions
jsonJSON data
csvCSV files
statisticsStatistical calculations
collectionsSpecialized containers
itertoolsIterator utilities
functoolsHigher-order functions
subprocessRun external processes
loggingApplication logging
argparseCommand-line arguments

Create Your Own Module

mymodule.py

def greet(name): return f"Hello {name}"

main.py

import mymodule print(mymodule.greet("Alex"))

Main Guard

def main(): print("Program started") if __name__ == "__main__": main()

17. Object-Oriented Programming (OOP)

OOP organizes programs using classes and objects.

Class and Object

class Student: def display(self): print("Hello Student") s1 = Student() s1.display()

Constructor

class Student: def __init__(self, name, age): self.name = name self.age = age s1 = Student("Alex", 20) print(s1.name) print(s1.age)

Instance Variables

class Student: def __init__(self, name): self.name = name

Class Variables

class Student: college = "ABC College" def __init__(self, name): self.name = name s1 = Student("Alex") print(s1.college)

Instance Methods

class Student: def show(self): print("Instance method")

Class Methods

class Student: college = "ABC College" @classmethod def change_college(cls, name): cls.college = name

Static Methods

class Calculator: @staticmethod def add(a, b): return a + b

Inheritance

class Animal: def sound(self): print("Animal sound") class Dog(Animal): def bark(self): print("Dog barks") d = Dog() d.sound() d.bark()

Types of Inheritance

Multiple Inheritance

class A: def show_a(self): print("Class A") class B: def show_b(self): print("Class B") class C(A, B): pass obj = C() obj.show_a() obj.show_b()

Method Overriding

class Animal: def sound(self): print("Animal sound") class Dog(Animal): def sound(self): print("Bark") d = Dog() d.sound()

super()

class Parent: def show(self): print("Parent class") class Child(Parent): def show(self): super().show() print("Child class") Child().show()

Encapsulation

Python uses naming conventions and name mangling rather than strict access modifiers.

class Bank: def __init__(self, balance): self.public = balance self._protected = balance self.__private = balance def get_balance(self): return self.__private

Properties

class Student: def __init__(self, marks): self._marks = marks @property def marks(self): return self._marks @marks.setter def marks(self, value): if value < 0: raise ValueError("Marks cannot be negative") self._marks = value s = Student(90) s.marks = 95

Polymorphism

class Cat: def sound(self): print("Meow") class Dog: def sound(self): print("Bark") for animal in [Cat(), Dog()]: animal.sound()

Abstract Classes

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2

18. Exception Handling

Exceptions are runtime errors that interrupt normal program execution.

try-except

try: a = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")

Multiple Exceptions

try: number = int(input("Enter number: ")) result = 10 / number except ValueError: print("Invalid input") except ZeroDivisionError: print("Cannot divide by zero")

else and finally

try: print(10 / 2) except ZeroDivisionError: print("Error") else: print("No exception occurred") finally: print("Execution completed")

Raise an Exception

age = 15 if age < 18: raise ValueError("Age must be 18 or above")

Custom Exception

class InvalidAgeError(Exception): pass age = 15 if age < 18: raise InvalidAgeError("Invalid age")

Common Built-in Exceptions

ExceptionMeaning
SyntaxErrorInvalid syntax
NameErrorUndefined name
TypeErrorInvalid operation for a type
ValueErrorInvalid value
IndexErrorInvalid sequence index
KeyErrorMissing dictionary key
ZeroDivisionErrorDivision by zero
AttributeErrorMissing attribute
ImportErrorImport failure
FileNotFoundErrorFile does not exist
ModuleNotFoundErrorModule cannot be found
RuntimeErrorGeneral runtime error
StopIterationIterator is exhausted

19. File Handling

Python supports reading and writing files.

Open a File

file = open("data.txt", "r") print(file.read()) file.close()

File Modes

ModeDescription
rRead
wWrite, overwrite existing content
aAppend
xCreate, fail if file exists
r+Read and write
w+Write and read, truncate
a+Append and read
bBinary mode modifier
tText mode modifier

Read a File

with open("data.txt", "r") as file: print(file.read())

Read One Line

with open("data.txt", "r") as file: print(file.readline())

Read All Lines

with open("data.txt", "r") as file: lines = file.readlines()

Write a File

with open("data.txt", "w") as file: file.write("Hello Python")

Append Data

with open("data.txt", "a") as file: file.write("\nNew Line")

File Position

with open("data.txt", "r") as file: print(file.tell()) file.seek(0)

Binary File Handling

with open("image.jpg", "rb") as file: data = file.read()

20. Working with Directories

Use os and pathlib for filesystem operations.

Using os

import os print(os.getcwd()) os.mkdir("new_folder") print(os.listdir()) if os.path.exists("data.txt"): print("File exists") os.rename("old.txt", "new.txt")

Using pathlib

from pathlib import Path path = Path("data.txt") print(path.exists()) print(path.name) print(path.suffix) print(path.parent) path.write_text("Hello Python") print(path.read_text())

21. List, Set, and Dictionary Comprehensions

List Comprehension

squares = [x ** 2 for x in range(10)]

Conditional List Comprehension

even = [x for x in range(20) if x % 2 == 0]

Set Comprehension

unique_squares = {x ** 2 for x in range(10)}

Dictionary Comprehension

squares = {x: x ** 2 for x in range(5)}

Nested Comprehension

matrix = [[j for j in range(3)] for i in range(3)]

22. Iterators and Generators

Iterator

An iterator is an object that implements __iter__() and __next__().

numbers = [10, 20, 30] it = iter(numbers) print(next(it)) print(next(it)) print(next(it))

Generator Function

Generators use yield to produce values lazily.

def generate_numbers(): yield 1 yield 2 yield 3 for number in generate_numbers(): print(number)

Generator Expression

squares = (x ** 2 for x in range(5)) for value in squares: print(value)

Advantages of Generators

23. Decorators

A decorator modifies or extends the behavior of a function without changing its source code.

Basic Decorator

def decorator(func): def wrapper(): print("Before function") func() print("After function") return wrapper @decorator def greet(): print("Hello") greet()

Decorator with Arguments

from functools import wraps def decorator(func): @wraps(func) def wrapper(*args, **kwargs): print("Function called") return func(*args, **kwargs) return wrapper @decorator def add(a, b): return a + b print(add(10, 20))

Common Built-in Decorators

24. Regular Expressions

The re module provides regular expression operations.

import re text = "Python is powerful"

Common Functions

re.match(r"Python", text) re.search(r"powerful", text) re.findall(r"\w+", text) re.sub(r"Python", "Java", text) re.split(r"\s+", text)

Common Regex Patterns

PatternMeaning
.Any character except newline by default
^Start of string
$End of string
*Zero or more
+One or more
?Zero or one
{n}Exactly n repetitions
{n,m}Between n and m repetitions
[]Character set
\dDigit
\DNon-digit
\wWord character
\WNon-word character
\sWhitespace
\SNon-whitespace
\bWord boundary

Email Pattern Example

import re email = "user@example.com" pattern = r"^[\w.-]+@[\w.-]+\.\w+$" if re.fullmatch(pattern, email): print("Valid format")

This is a basic format check, not complete email validation.

25. Date and Time

Use the datetime module.

from datetime import datetime, date, time, timedelta now = datetime.now() today = date.today() print(now) print(today)

Create a Date

d = date(2026, 11, 7) print(d)

Format Date

now = datetime.now() print(now.strftime("%d-%m-%Y")) print(now.strftime("%H:%M:%S"))

Parse Date

date_string = "07-11-2026" d = datetime.strptime(date_string, "%d-%m-%Y") print(d)

Date Arithmetic

today = date.today() tomorrow = today + timedelta(days=1) yesterday = today - timedelta(days=1) print(tomorrow) print(yesterday)

26. JSON Handling

JSON is commonly used for exchanging structured data.

import json student = { "name": "Alex", "age": 20 }

Python Object to JSON String

json_data = json.dumps(student, indent=4) print(json_data)

JSON String to Python Object

data = json.loads(json_data) print(data["name"])

Write JSON File

with open("student.json", "w") as file: json.dump(student, file, indent=4)

Read JSON File

with open("student.json", "r") as file: data = json.load(file)

27. CSV Handling

Use the built-in csv module.

Write CSV

import csv data = [ ["Name", "Age"], ["Alex", 20], ["John", 21] ] with open("students.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(data)

Read CSV

import csv with open("students.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)

Dictionary-Based CSV

import csv with open("students.csv", "w", newline="") as file: fieldnames = ["name", "age"] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({"name": "Alex", "age": 20})

28. Useful Built-in Functions

FunctionDescription
print()Display output
input()Read user input
type()Return object type
id()Return object identity
len()Return length
range()Generate integer sequence
sum()Sum iterable values
min()Minimum value
max()Maximum value
abs()Absolute value
round()Round a number
pow()Exponentiation
sorted()Return sorted list
reversed()Return reverse iterator
enumerate()Get index and value
zip()Combine iterables
map()Apply function to items
filter()Filter iterable
any()True if any item is true
all()True if all items are true
isinstance()Check object type
issubclass()Check class inheritance
callable()Check if object is callable
eval()Evaluate expression
exec()Execute code
help()Display documentation
dir()List attributes

enumerate()

names = ["Alex", "John", "Sam"] for index, name in enumerate(names, start=1): print(index, name)

zip()

names = ["Alex", "John"] ages = [20, 21] for name, age in zip(names, ages): print(name, age)

map()

numbers = [1, 2, 3, 4] squares = list(map(lambda x: x ** 2, numbers)) print(squares)

filter()

numbers = [1, 2, 3, 4, 5, 6] even = list(filter(lambda x: x % 2 == 0, numbers)) print(even)

any() and all()

numbers = [2, 4, 6] print(any(x > 5 for x in numbers)) print(all(x % 2 == 0 for x in numbers))

29. Useful Standard Library Collections

Counter

from collections import Counter data = ["A", "B", "A", "C", "A"] count = Counter(data) print(count) print(count.most_common(1))

defaultdict

from collections import defaultdict data = defaultdict(list) data["fruits"].append("Apple") data["fruits"].append("Mango")

deque

from collections import deque queue = deque([1, 2, 3]) queue.append(4) queue.appendleft(0) queue.pop() queue.popleft()

namedtuple

from collections import namedtuple Student = namedtuple("Student", ["name", "age"]) s = Student("Alex", 20) print(s.name) print(s.age)

30. Functional Programming Tools

Lambda

square = lambda x: x * x

map()

result = list(map(str.upper, ["python", "java"]))

filter()

result = list(filter(lambda x: x > 10, [5, 15, 20]))

reduce()

from functools import reduce numbers = [1, 2, 3, 4] result = reduce(lambda a, b: a + b, numbers) print(result)

31. Working with Random Numbers

import random print(random.random()) print(random.randint(1, 10)) print(random.randrange(1, 20, 2)) items = ["Python", "Java", "C++"] print(random.choice(items)) random.shuffle(items) print(items) print(random.sample(items, 2))

Reproducible Random Values

random.seed(42) print(random.randint(1, 100))

For security-sensitive random values, use the secrets module instead of random.

32. Command-Line Arguments

Use sys.argv for basic argument handling.

import sys print(sys.argv)

argparse

import argparse parser = argparse.ArgumentParser() parser.add_argument("--name", required=True) parser.add_argument("--age", type=int, default=18) args = parser.parse_args() print(args.name) print(args.age)

Run:

python main.py --name Alex --age 20

33. Working with the Operating System

Environment Variables

import os print(os.environ.get("PATH"))

Create a Directory

import os os.makedirs("projects/python", exist_ok=True)

Run a Command

import subprocess result = subprocess.run( ["python", "--version"], capture_output=True, text=True ) print(result.stdout)

Avoid passing untrusted input to shell commands.

34. Logging

Logging records application events and errors.

import logging logging.basicConfig( level=logging.INFO, format="%(levelname)s: %(message)s" ) logging.debug("Debug message") logging.info("Application started") logging.warning("Warning message") logging.error("An error occurred") logging.critical("Critical error")

Logging Levels

LevelDescription
DEBUGDetailed debugging information
INFOGeneral information
WARNINGUnexpected situation
ERROROperation failed
CRITICALSerious failure

35. Type Hints

Type hints improve readability and help static analysis tools.

name: str = "Alex" age: int = 20 price: float = 99.5 active: bool = True

Function Type Hints

def add(a: int, b: int) -> int: return a + b

Collections

numbers: list[int] = [1, 2, 3] student: dict[str, int] = { "Alex": 90, "John": 85 }

Optional Values

def find_name(name: str | None) -> str: return name if name is not None else "Unknown"

36. Context Managers

Context managers handle setup and cleanup operations.

Using with

with open("data.txt", "r") as file: content = file.read()

Custom Context Manager

from contextlib import contextmanager @contextmanager def managed_resource(): print("Resource opened") try: yield finally: print("Resource closed") with managed_resource(): print("Using resource")

37. Asynchronous Programming

Python supports asynchronous programming using asyncio.

Async Function

import asyncio async def greet(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(greet())

Multiple Async Tasks

import asyncio async def task(name): print(f"Starting {name}") await asyncio.sleep(1) print(f"Finished {name}") async def main(): await asyncio.gather( task("Task 1"), task("Task 2") ) asyncio.run(main())

Async Iterator

import asyncio async def numbers(): for i in range(3): yield i await asyncio.sleep(0.1) async def main(): async for value in numbers(): print(value) asyncio.run(main())

38. Threading and Multiprocessing

Threading

Useful for I/O-bound tasks.

import threading def task(): print("Thread running") t = threading.Thread(target=task) t.start() t.join()

Multiprocessing

Useful for CPU-bound tasks.

from multiprocessing import Process def task(): print("Process running") if __name__ == "__main__": p = Process(target=task) p.start() p.join()

39. Database Connectivity with SQLite

SQLite is included in Python's standard library.

import sqlite3 connection = sqlite3.connect("students.db") cursor = connection.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ) """) cursor.execute( "INSERT INTO students (name, age) VALUES (?, ?)", ("Alex", 20) ) connection.commit() cursor.execute("SELECT * FROM students") for row in cursor.fetchall(): print(row) connection.close()

Use parameterized queries (?) instead of building SQL statements with string concatenation.

40. Popular Python Libraries

Web Development

LibraryPurpose
DjangoFull-stack web framework
FlaskLightweight web framework
FastAPIAPI development
RequestsHTTP requests
BeautifulSoupHTML parsing

Data Science

LibraryPurpose
NumPyNumerical computing
PandasData analysis
MatplotlibData visualization
SeabornStatistical visualization
SciPyScientific computing

AI and Machine Learning

LibraryPurpose
Scikit-learnMachine learning
TensorFlowDeep learning
PyTorchDeep learning
KerasNeural networks
TransformersPretrained AI models

Automation and Testing

LibraryPurpose
SeleniumBrowser automation
PlaywrightBrowser automation
PyAutoGUIDesktop automation
PytestTesting
unittestBuilt-in testing framework

Cybersecurity and Networking

LibraryPurpose
ScapyPacket manipulation and analysis
RequestsHTTP communication
ParamikoSSH connectivity
SocketNetwork programming
CryptographyCryptographic operations
dnspythonDNS toolkit

41. Python Virtual Environments

Virtual environments isolate project dependencies.

Create Environment

python -m venv venv

Activate on Linux/macOS

source venv/bin/activate

Activate on Windows

venv\Scripts\activate

Install Packages

python -m pip install requests

List Packages

python -m pip list

Save Dependencies

python -m pip freeze > requirements.txt

Install Dependencies

python -m pip install -r requirements.txt

Deactivate

deactivate

42. Python Package Management

Install Package

python -m pip install package_name

Upgrade Package

python -m pip install --upgrade package_name

Uninstall Package

python -m pip uninstall package_name

Show Package Information

python -m pip show package_name

Upgrade pip

python -m pip install --upgrade pip

43. Unit Testing

Using unittest

import unittest def add(a, b): return a + b class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) if __name__ == "__main__": unittest.main()

Common Assertions

AssertionPurpose
assertEqual(a, b)Values are equal
assertNotEqual(a, b)Values differ
assertTrue(x)Condition is true
assertFalse(x)Condition is false
assertIs(a, b)Same object
assertIsNone(x)Value is None
assertIn(a, b)Item exists in container
assertRaises(E)Exception is raised

Run Tests

python -m unittest

44. Python Debugging

print() Debugging

x = 10 print("Value of x:", x)

Using breakpoint()

x = 10 y = 20 breakpoint() print(x + y)

Using pdb

import pdb pdb.set_trace()

45. Modern Python Features

FeatureVersion
f-stringsPython 3.6+
Data classesPython 3.7+
Assignment expression :=Python 3.8+
Dictionary union |Python 3.9+
Structural pattern matchingPython 3.10+
Exception groupsPython 3.11+
type statement for aliasesPython 3.12+
Template string literals (t-strings)Python 3.14+

Walrus Operator

if (length := len("Python")) > 5: print(length)

Dataclasses

from dataclasses import dataclass @dataclass class Student: name: str age: int s = Student("Alex", 20) print(s)

Pattern Matching

command = "start" match command: case "start": print("Starting") case "stop": print("Stopping") case _: print("Unknown command")

46. Important Python Concepts

Mutable and Immutable Objects

MutableImmutable
listint
dictfloat
setbool
bytearraystr
tuple
frozenset
bytes

A tuple is immutable, but it can contain mutable objects.

Shallow Copy

import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original)

Deep Copy

deep = copy.deepcopy(original)

Unpacking

a, b = 10, 20 first, *middle, last = [1, 2, 3, 4, 5]

Swapping Variables

a = 10 b = 20 a, b = b, a

Truthy and Falsy Values

Common falsy values:

False None 0 0.0 "" [] {} set() ()

Most other objects are truthy.

47. Common Programming Problems

Swap Two Numbers

a = 10 b = 20 a, b = b, a

Even or Odd

n = 10 if n % 2 == 0: print("Even") else: print("Odd")

Factorial

n = 5 fact = 1 for i in range(1, n + 1): fact *= i print(fact)

Fibonacci Series

a, b = 0, 1 for i in range(10): print(a, end=" ") a, b = b, a + b

Prime Number

n = 17 if n < 2: print("Not Prime") else: for i in range(2, int(n ** 0.5) + 1): if n % i == 0: print("Not Prime") break else: print("Prime")

Reverse a String

text = "Python" print(text[::-1])

Palindrome

text = "madam" if text == text[::-1]: print("Palindrome") else: print("Not Palindrome")

Armstrong Number

n = 153 digits = str(n) total = sum(int(d) ** len(digits) for d in digits) if total == n: print("Armstrong Number") else: print("Not Armstrong")

Find Largest Number

numbers = [10, 50, 30, 20] print(max(numbers))

Remove Duplicates

numbers = [1, 2, 2, 3, 3, 4] unique = list(dict.fromkeys(numbers)) print(unique)

Count Vowels

text = "Python Programming" count = sum(1 for char in text.lower() if char in "aeiou") print(count)

Character Frequency

from collections import Counter text = "programming" frequency = Counter(text) print(frequency)

48. Time Complexity Quick Reference

OperationAverage Time Complexity
List indexingO(1)
List appendO(1) amortized
List insertion at beginningO(n)
List searchO(n)
List sortingO(n log n)
Tuple indexingO(1)
Dictionary lookupO(1) average
Dictionary insertionO(1) average
Set membershipO(1) average
Linear searchO(n)
Binary searchO(log n)
Merge sortO(n log n)

Complexities are typical average-case values; exact behavior can depend on implementation and input.

49. Common Python Errors

ErrorCause
SyntaxErrorInvalid syntax
IndentationErrorIncorrect indentation
NameErrorUndefined variable
TypeErrorUnsupported operation
ValueErrorInvalid value
IndexErrorInvalid index
KeyErrorMissing dictionary key
ZeroDivisionErrorDivision by zero
AttributeErrorInvalid attribute access
FileNotFoundErrorFile not found
ImportErrorImport problem
ModuleNotFoundErrorMissing module
RecursionErrorMaximum recursion depth exceeded

Tips to Avoid Errors

50. Python Best Practices

  1. Follow PEP 8 style guidelines.
  2. Use meaningful variable and function names.
  3. Keep functions small and reusable.
  4. Avoid unnecessary global variables.
  5. Use context managers for files and resources.
  6. Handle exceptions appropriately.
  7. Use virtual environments for projects.
  8. Write documentation and docstrings.
  9. Add tests for important functionality.
  10. Prefer readable code over unnecessarily clever code.
  11. Use type hints where they improve clarity.
  12. Avoid hardcoding passwords and API keys.
  13. Keep dependencies updated.
  14. Use version control such as Git.
  15. Avoid eval() and exec() with untrusted input.

51. Python Syntax Quick Reference

# Variable name = "Alex" # Input name = input("Enter name: ") # Output print(name) # Condition if condition: pass elif another_condition: pass else: pass # For loop for item in iterable: pass # While loop while condition: pass # Function def function_name(parameters): return result # Lambda square = lambda x: x ** 2 # List items = [1, 2, 3] # Tuple items = (1, 2, 3) # Set items = {1, 2, 3} # Dictionary data = {"name": "Alex"} # Class class Student: def __init__(self, name): self.name = name # Exception handling try: pass except Exception as error: print(error) finally: pass # File handling with open("file.txt", "r") as file: content = file.read() # Import import math # Main guard if __name__ == "__main__": pass

52. Useful Python Resources

Official Documentation

Conclusion

Python is a versatile programming language used in software development, automation, web development, data science, artificial intelligence, and cybersecurity.

This cheatsheet provides a quick reference to Python syntax, programming concepts, built-in functions, libraries, and practical examples. Use it alongside hands-on coding and real-world projects to strengthen your programming skills.