🧠 AI Computer Institute
Content is AI-generated for educational purposes. Verify critical information independently. A bharath.ai initiative.

Python Basics Cheat Sheet

programmingGrades 7-129 sections

Visual Overview: Python Type Hierarchy

Python Type Hierarchy object numeric sequences mappings & sets int float complex str list tuple dict set Key Properties: Mutable (changeable): • list - ordered, indexed • dict - key-value pairs • set - unique values Immutable (unchangeable): • int, float, complex - numbers • str - text (sequences) • tuple - ordered collection

All Python objects inherit from the base object class and branch into major type categories

Data Types & Variables

TypeExampleNotes
intx = 42Unlimited precision
floatx = 3.14Decimal numbers
strx = "hello"Immutable sequences
boolx = TrueTrue or False
listx = [1, 2, 3]Mutable, ordered
tuplex = (1, 2, 3)Immutable, ordered
dictx = {"a": 1}Key-value pairs
setx = {1, 2, 3}Unique, unordered

Type Casting: int(), str(), float(), bool(), list(), tuple()

String Methods

MethodExampleOutput
upper()"hello".upper()"HELLO"
lower()"HELLO".lower()"hello"
strip()" hi ".strip()"hi"
split()"a,b,c".split(",")["a", "b", "c"]
join()"-".join(["a","b"])"a-b"
replace()"hi".replace("i","o")"ho"
find()"hello".find("l")2
startswith()"hello".startswith("he")True

Loops & Control Flow

# if-elif-else
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

# for loop
for i in range(5):
    print(i)  # 0,1,2,3,4

# while loop
while x > 0:
    print(x)
    x -= 1

# break and continue
for i in range(10):
    if i == 3:
        continue
    if i == 7:
        break
    print(i)

Functions

# Basic function
def greet(name):
    return f"Hello, {name}!"

# Default arguments
def add(a, b=0):
    return a + b

# *args (variable positional)
def sum_all(*numbers):
    return sum(numbers)

# **kwargs (variable keyword)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Lambda (anonymous)
square = lambda x: x**2
print(square(5))  # 25

List Comprehensions

# Basic list comprehension
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]

# With condition (filter)
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

# Nested comprehension
matrix = [[i+j for j in range(3)] for i in range(3)]

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Set comprehension
unique_chars = {char for word in words for char in word}

File I/O & Exception Handling

# File operations
with open("file.txt", "r") as f:
    content = f.read()  # entire file
    lines = f.readlines()  # list of lines

# Write to file
with open("file.txt", "w") as f:
    f.write("Hello")

# Exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup code")

Useful Built-in Functions

FunctionExampleOutput
len()len([1,2,3])3
max()max([3,1,4])4
min()min([3,1,4])1
sum()sum([1,2,3])6
abs()abs(-5)5
round()round(3.7)4
sorted()sorted([3,1,2])[1,2,3]
enumerate()enumerate(["a","b"])Index-value pairs
zip()zip([1,2], ["a","b"])[(1,"a"),(2,"b")]
map()map(str, [1,2])["1","2"]

String Formatting

# f-strings (Python 3.6+)
name = "Raj"
age = 16
print(f"I am {name}, {age} years old")

# format() method
"Hello, {}!".format("world")
"{1} {0}".format("world", "Hello")
"{name} is {age}".format(name="Priya", age=15)

# Old-style % formatting (legacy)
"Hello %s" % "world"

# Alignment and padding
f"{name:>10}"  # Right-align in 10 chars
f"{age:05d}"   # Zero-pad to 5 digits
f"{3.14159:.2f}"  # Round to 2 decimals

More Cheat Sheets