Python Cheat Sheet

Return to TOC

Basic Syntax

print("Hello, World!")

Variables and Data Types

Data Type Description Example
int Integer x = 5
float Floating-point number y = 3.14
str String name = "Alice"
bool Boolean is_valid = True
list List fruits = ["apple", "banana", "cherry"]
tuple Tuple point = (1, 2)
dict Dictionary person = {"name": "Alice", "age": 25}
set Set colors = {"red", "green", "blue"}

Control Flow

Statement Description Example
if Conditional statement if x > 0:
    print("Positive")
elif Else if statement elif x == 0:
    print("Zero")
else Else statement else:
    print("Negative")
for For loop for i in range(5):
    print(i)
while While loop while x > 0:
    x -= 1
break Break out of a loop break
continue Continue to the next iteration of a loop continue

Functions

Function Description Example
def Define a function def greet(name):
    print(f"Hello, {name}!")
return Return a value from a function return x + y

Modules

Import Description Example
import Import a module import math
from ... import ... Import specific attributes from a module from math import sqrt
as Import a module with an alias import numpy as np

File Handling

Operation Description Example
open Open a file f = open("file.txt")
read Read a file content = f.read()
write Write to a file f.write("Hello, World!")
close Close a file f.close()
with Context manager for file operations with open("file.txt") as f:
    content = f.read()

Exceptions

Statement Description Example
try Try to execute a block of code try:
    print(x)
except Handle exceptions except Exception as e:
    print(e)
finally Execute code regardless of exceptions finally:
    print("Done")

Classes and Objects

Statement Description Example
class Define a class class Dog:
    def __init__(self, name):
        self.name = name
__init__ Initialize an instance of a class def __init__(self, name):
    self.name = name
self Reference to the instance of the class self.name = name
method Define a method in a class def bark(self):
    print("Woof!")
object Create an instance of a class my_dog = Dog("Buddy")

List Comprehensions

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

Common Libraries

Library Description Example
math Mathematical functions import math
math.sqrt(16)
random Generate random numbers import random
random.randint(1, 10)
datetime Manipulate dates and times import datetime
datetime.datetime.now()
os Interacting with the operating system import os
os.getcwd()
sys System-specific parameters and functions import sys
sys.exit()
json JSON encoder and decoder import json
json.dumps({"name": "Alice", "age": 25})