Python Programming Cheat Sheet

Basic Syntax

ConceptSyntaxExample
Comments# comment# This is a comment
Print Statementprint(value)print("Hello World")
Input Statementinput(prompt)name = input("Enter name: ")
Multi-line Comment""" comment """"""This is a multi-line comment"""

Data Types

TypeExampleDescription
intx = 10Integer number
floaty = 3.14Floating point number
strname = "Python"String of characters
boolflag = TrueBoolean value (True/False)
listitems = [1, 2, 3]Ordered, mutable collection
tuplepoint = (1, 2)Ordered, immutable collection
dictperson = {"name": "John"}Key-value pairs
setunique = {1, 2, 3}Unordered unique items

Operators

CategoryOperatorExampleDescription
Arithmetic+ - * / // % **5 + 3 = 8Addition, Subtraction, Multiplication, Division, Floor Division, Modulus, Exponentiation
Comparison== != < > <= >=5 == 5 is TrueEquality, Inequality, Less/Greater than, etc.
Logicaland or notTrue and False is FalseLogical AND, OR, NOT
Assignment= += -= *= /= //= %= **= &= |= ^= >>= <<=x += 5Assignment operators
Membershipin not in3 in [1,2,3] is TrueCheck if value is in sequence
Identityis is notx is yCheck if objects are identical

Control Structures

StructureSyntaxExample
If Statementif condition:
    statement
if x > 0:
    print("Positive")
If-Elif-Elseif c1:
    s1
elif c2:
    s2
else:
    s3
if x > 0:
    print("Pos")
elif x == 0:
    print("Zero")
else:
    print("Neg")
For Loopfor item in iterable:
    statement
for i in range(5):
    print(i)
While Loopwhile condition:
    statement
while x > 0:
    x -= 1
Breakbreakfor i in range(10):
    if i == 5:
        break
Continuecontinuefor i in range(5):
    if i == 2:
        continue
    print(i)

Functions

ConceptSyntaxExample
Function Definitiondef name(params):
    body
def greet(name):
    return f"Hello {name}"
Function Callname(arguments)result = greet("John")
Default Parametersdef func(p=value):def greet(name="World"):
Keyword Argumentsfunc(param=value)func(name="John", age=25)
Variable Arguments*args, **kwargsdef func(*args, **kwargs):
Lambda Functionlambda params: expressionsquare = lambda x: x**2

Lists

OperationSyntaxExample
Create Listlist = [items]nums = [1, 2, 3]
Access Elementlist[index]first = nums[0]
Add Elementlist.append(item)nums.append(4)
Insert Elementlist.insert(index, item)nums.insert(1, 10)
Remove Elementlist.remove(item)nums.remove(2)
Pop Elementlist.pop(index)last = nums.pop()
List Slicinglist[start:end:step]subset = nums[1:4]
List Comprehension[expr for item in list]squares = [x**2 for x in range(5)]

Dictionaries

OperationSyntaxExample
Create Dictdict = {key: value}person = {"name": "John", "age": 25}
Access Valuedict[key]name = person["name"]
Add/Updatedict[key] = valueperson["city"] = "NYC"
Get Valuedict.get(key)age = person.get("age", 0)
Keysdict.keys()keys = person.keys()
Valuesdict.values()values = person.values()
Itemsdict.items()items = person.items()
Delete Keydel dict[key]del person["age"]

String Operations

OperationSyntaxExample
Lengthlen(string)length = len("hello")
Concatenationstr1 + str2result = "Hello" + " " + "World"
Repetitionstring * nstars = "*" * 5
Indexingstring[index]first = "hello"[0]
Slicingstring[start:end]part = "hello"[1:4]
Upper Casestring.upper()caps = "hello".upper()
Lower Casestring.lower()lower = "HELLO".lower()
Replacestring.replace(old, new)new = "hello".replace("l", "x")
Splitstring.split(separator)parts = "a,b,c".split(",")
Joinseparator.join(list)result = "-".join(["a", "b", "c"])

File Operations

OperationSyntaxExample
Open Fileopen(filename, mode)f = open("file.txt", "r")
Read Filefile.read()content = f.read()
Read Linesfile.readlines()lines = f.readlines()
Write Filefile.write(text)f.write("Hello World")
Close Filefile.close()f.close()
Context Managerwith open(...) as f:with open("file.txt", "r") as f:
    content = f.read()

Error Handling

StructureSyntaxExample
Try-Excepttry:
    statements
except Error:
    handler
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
Try-Except-Elsetry:
    ...
except ...:
    ...
else:
    ...
try:
    x = int(input())
except ValueError:
    print("Invalid")
else:
    print("Valid")
Try-Except-Finallytry:
    ...
except ...:
    ...
finally:
    ...
try:
    f = open("file.txt")
    ...
finally:
    f.close()

Classes and Objects

ConceptSyntaxExample
Class Definitionclass Name:
    def __init__(self):
class Person:
    def __init__(self, name):
        self.name = name
Object Creationobj = ClassName()p = Person("John")
Method Definitiondef method(self):def greet(self):
    return f"Hello {self.name}"
Inheritanceclass Child(Parent):class Student(Person):
    def __init__(self, name, grade):
        super().__init__(name)
        self.grade = grade

Common Built-in Functions

FunctionUsageExample
len()Get length of objectlen([1,2,3]) returns 3
type()Get type of objecttype(42) returns <class 'int'>
str()Convert to stringstr(42) returns "42"
int()Convert to integerint("42") returns 42
float()Convert to floatfloat("3.14") returns 3.14
list()Convert to listlist("abc") returns ['a', 'b', 'c']
range()Create range objectrange(5) creates 0,1,2,3,4
enumerate()Get index and valuefor i, v in enumerate(list)
zip()Combine iterableszip([1,2], ['a','b'])
map()Apply function to itemsmap(func, [1,2,3])
filter()Filter items with functionfilter(func, [1,2,3])
sum()Sum of numberssum([1,2,3]) returns 6
max()Maximum valuemax([1,2,3]) returns 3
min()Minimum valuemin([1,2,3]) returns 1