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
- Easy to learn and use
- Interpreted language
- Dynamically typed
- Object-oriented and functional programming support
- Cross-platform
- Large standard library
- Open-source
- Supports automation, web development, AI, data science, and cybersecurity
Applications
- Web Development
- Data Science
- Artificial Intelligence and Machine Learning
- Cybersecurity and Ethical Hacking
- Automation and Scripting
- IoT and Embedded Systems
- Software Development
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
- Must start with a letter or underscore.
- Cannot start with a number.
- Can contain letters, numbers, and underscores.
- Case-sensitive.
- Cannot use Python keywords.
- Use descriptive names.
user_name = "Alex" total_marks = 450 _private = 100
Naming Conventions
| Type | Convention | Example |
|---|---|---|
| Variable | snake_case | user_name |
| Function | snake_case | calculate_total() |
| Class | PascalCase | StudentRecord |
| Constant | UPPER_CASE | MAX_SIZE |
| Private convention | Leading 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.
| Category | Data Type | Example |
|---|---|---|
| Numeric | int | 100 |
| Numeric | float | 10.5 |
| Numeric | complex | 2 + 3j |
| Boolean | bool | True |
| Text | str | "Python" |
| Sequence | list | [1, 2, 3] |
| Sequence | tuple | (1, 2, 3) |
| Sequence | range | range(5) |
| Mapping | dict | {"name": "Alex"} |
| Set | set | {1, 2, 3} |
| Set | frozenset | frozenset({1, 2}) |
| Binary | bytes | b"Hello" |
| Binary | bytearray | bytearray(5) |
| Binary | memoryview | memoryview(bytes(5)) |
| None | NoneType | None |
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
| Operator | Description | Example |
|---|---|---|
| + | Addition | 10 + 5 |
| - | Subtraction | 10 - 5 |
| * | Multiplication | 10 * 5 |
| / | Division | 10 / 5 |
| // | Floor division | 10 // 3 |
| % | Modulus | 10 % 3 |
| ** | Exponentiation | 2 ** 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
| Operator | Meaning |
|---|---|
| == | 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
| Operator | Description |
|---|---|
| and | True if both conditions are true |
| or | True if at least one condition is true |
| not | Reverses 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
| Operator | Description |
|---|---|
| & | 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:
- Local
- Enclosing
- Global
- 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
| Module | Purpose |
|---|---|
| math | Mathematical functions |
| random | Random numbers |
| os | Operating system operations |
| sys | Python interpreter utilities |
| pathlib | File paths |
| datetime | Date and time |
| time | Time-related functions |
| re | Regular expressions |
| json | JSON data |
| csv | CSV files |
| statistics | Statistical calculations |
| collections | Specialized containers |
| itertools | Iterator utilities |
| functools | Higher-order functions |
| subprocess | Run external processes |
| logging | Application logging |
| argparse | Command-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
- Single inheritance
- Multiple inheritance
- Multilevel inheritance
- Hierarchical inheritance
- Hybrid 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
| Exception | Meaning |
|---|---|
| SyntaxError | Invalid syntax |
| NameError | Undefined name |
| TypeError | Invalid operation for a type |
| ValueError | Invalid value |
| IndexError | Invalid sequence index |
| KeyError | Missing dictionary key |
| ZeroDivisionError | Division by zero |
| AttributeError | Missing attribute |
| ImportError | Import failure |
| FileNotFoundError | File does not exist |
| ModuleNotFoundError | Module cannot be found |
| RuntimeError | General runtime error |
| StopIteration | Iterator 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
| Mode | Description |
|---|---|
| r | Read |
| w | Write, overwrite existing content |
| a | Append |
| x | Create, fail if file exists |
| r+ | Read and write |
| w+ | Write and read, truncate |
| a+ | Append and read |
| b | Binary mode modifier |
| t | Text 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
- Memory efficient
- Lazy evaluation
- Useful for large datasets
- Values are generated when needed
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
@staticmethod@classmethod@property@abstractmethod@functools.wraps
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
| Pattern | Meaning |
|---|---|
| . | 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 |
| \d | Digit |
| \D | Non-digit |
| \w | Word character |
| \W | Non-word character |
| \s | Whitespace |
| \S | Non-whitespace |
| \b | Word 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
| Function | Description |
|---|---|
| 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
| Level | Description |
|---|---|
| DEBUG | Detailed debugging information |
| INFO | General information |
| WARNING | Unexpected situation |
| ERROR | Operation failed |
| CRITICAL | Serious 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
| Library | Purpose |
|---|---|
| Django | Full-stack web framework |
| Flask | Lightweight web framework |
| FastAPI | API development |
| Requests | HTTP requests |
| BeautifulSoup | HTML parsing |
Data Science
| Library | Purpose |
|---|---|
| NumPy | Numerical computing |
| Pandas | Data analysis |
| Matplotlib | Data visualization |
| Seaborn | Statistical visualization |
| SciPy | Scientific computing |
AI and Machine Learning
| Library | Purpose |
|---|---|
| Scikit-learn | Machine learning |
| TensorFlow | Deep learning |
| PyTorch | Deep learning |
| Keras | Neural networks |
| Transformers | Pretrained AI models |
Automation and Testing
| Library | Purpose |
|---|---|
| Selenium | Browser automation |
| Playwright | Browser automation |
| PyAutoGUI | Desktop automation |
| Pytest | Testing |
| unittest | Built-in testing framework |
Cybersecurity and Networking
| Library | Purpose |
|---|---|
| Scapy | Packet manipulation and analysis |
| Requests | HTTP communication |
| Paramiko | SSH connectivity |
| Socket | Network programming |
| Cryptography | Cryptographic operations |
| dnspython | DNS 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
| Assertion | Purpose |
|---|---|
| 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
| Feature | Version |
|---|---|
| f-strings | Python 3.6+ |
| Data classes | Python 3.7+ |
Assignment expression := | Python 3.8+ |
Dictionary union | | Python 3.9+ |
| Structural pattern matching | Python 3.10+ |
| Exception groups | Python 3.11+ |
type statement for aliases | Python 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
| Mutable | Immutable |
|---|---|
| list | int |
| dict | float |
| set | bool |
| bytearray | str |
| 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
| Operation | Average Time Complexity |
|---|---|
| List indexing | O(1) |
| List append | O(1) amortized |
| List insertion at beginning | O(n) |
| List search | O(n) |
| List sorting | O(n log n) |
| Tuple indexing | O(1) |
| Dictionary lookup | O(1) average |
| Dictionary insertion | O(1) average |
| Set membership | O(1) average |
| Linear search | O(n) |
| Binary search | O(log n) |
| Merge sort | O(n log n) |
Complexities are typical average-case values; exact behavior can depend on implementation and input.
49. Common Python Errors
| Error | Cause |
|---|---|
| SyntaxError | Invalid syntax |
| IndentationError | Incorrect indentation |
| NameError | Undefined variable |
| TypeError | Unsupported operation |
| ValueError | Invalid value |
| IndexError | Invalid index |
| KeyError | Missing dictionary key |
| ZeroDivisionError | Division by zero |
| AttributeError | Invalid attribute access |
| FileNotFoundError | File not found |
| ImportError | Import problem |
| ModuleNotFoundError | Missing module |
| RecursionError | Maximum recursion depth exceeded |
Tips to Avoid Errors
- Use consistent indentation.
- Check variable names.
- Validate user input.
- Handle exceptions.
- Test boundary conditions.
- Use meaningful names.
- Read error messages carefully.
50. Python Best Practices
- Follow PEP 8 style guidelines.
- Use meaningful variable and function names.
- Keep functions small and reusable.
- Avoid unnecessary global variables.
- Use context managers for files and resources.
- Handle exceptions appropriately.
- Use virtual environments for projects.
- Write documentation and docstrings.
- Add tests for important functionality.
- Prefer readable code over unnecessarily clever code.
- Use type hints where they improve clarity.
- Avoid hardcoding passwords and API keys.
- Keep dependencies updated.
- Use version control such as Git.
- Avoid
eval()andexec()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
- Python Documentation: https://docs.python.org/3/
- Python Tutorial: https://docs.python.org/3/tutorial/
- Python Standard Library: https://docs.python.org/3/library/
- Python Package Index: https://pypi.org/
- PEP 8 Style Guide: https://peps.python.org/pep-0008/
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.