Python cheatsheet Quick Reference
A concise and beginner-friendly Python cheatsheet covering essential syntax, data types, loops, functions, and more for quick reference.
Getting Started
Introduction
Click here to read more# This is a comment in Python, used to annotate code
# Print statement
print("Hello, World!") # Outputs: Hello, World!
# Variables and basic data types
name = "Alice" # String
age = 30 # Integer
height = 5.6 # Float
is_student = True # Boolean
# Basic math
sum = age + 5 # Adds 5 to age (30 + 5 = 35)
product = age * 2 # Multiplies age by 2 (30 * 2 = 60)
# List (Array)
fruits = ["apple", "banana", "cherry"]
# Loop through list
for fruit in fruits:
print(fruit)
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call the function
print(greet(name)) # Outputs: Hello, Alice!
See: Python
Hello World
>>> print("Hello, World!")
Hello, World!
Variables
age = 18 # 'age' is assigned as an integer
name = "John" # 'name' is assigned as a string
print(name) # Outputs the value of 'name'
Data Types
str # Text type
int, float, complex # Numeric types
list, tuple, range # Sequence types
dict # Mapping type
set, frozenset # Set types
bool # Boolean type
bytes, bytearray, memoryview # Binary types
Slicing String
>>> msg = "Hello, World!"
>>> print(msg[2:5]) # Output: llo
Lists
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # Outputs: 1, 2
If Else
number = 200 # number holds an integer value
if number > 0:
print("number is greater than 0")
else:
print("number is not greater than 0")
Loops
for value in range(6): # Iterate through numbers from 0 to 5
if value == 3: # If the value is 3, exit the loop
break
print(value) # Print the current value
else:
print("Loop completed!") # This executes if the loop is not terminated by 'break'
Functions
def my_function(): # Define a function named 'my_function'
print("Hello from a function") # Print a greeting message
my_function() # Call the function to execute its code
File Handling
with open("myfile.txt", "r", encoding='utf-8') as f:
for line in f:
print(line.strip()) # Using strip() to remove any leading/trailing whitespace
Arithmetic
result = 10 + 30 # Addition: 10 + 30 = 40
result = 40 - 10 # Subtraction: 40 - 10 = 30
result = 50 * 5 # Multiplication: 50 * 5 = 250
result = 16 / 4 # Float Division: 16 / 4 = 4.0
result = 16 // 4 # Integer Division: 16 // 4 = 4 (floored quotient)
result = 25 % 2 # Modulus: 25 % 2 = 1 (remainder)
result = 5 ** 3 # Exponentiation: 5 raised to the power of 3 = 125
# Note: The '/' operator performs float division, while '//' performs integer (floored) division.
Plus-Equals
counter = 0
counter += 10 # Increment counter by 10; counter now equals 10
counter = 0
counter = counter + 10 # Add 10 to counter; counter now equals 10
message = "Part 1." # Initialize message with "Part 1."
# Append "Part 2." to the message
message += "Part 2." # message now equals "Part 1.Part 2."
f-Strings (Python 3.6+)
website = 'Quickref.ME' # Assign the string 'Quickref.ME' to the variable 'website'
greeting = f"Hello, {website}" # Use an f-string to include 'website' in the greeting
# Result: "Hello, Quickref.ME"
num = 10 # Assign the integer 10 to the variable 'num'
expression = f'{num} + 10 = {num + 10}' # Use an f-string to show the calculation
# Result: '10 + 10 = 20'
Python Built-in Data Types
Strings
greeting1 = "Hello World" # Assigning a string to 'greeting1' using double quotes
greeting2 = 'Hello World' # Assigning a string to 'greeting2' using single quotes
# Defining a multiline string using triple quotes
multiline_string = """Multiline Strings
Lorem ipsum dolor sit amet,
consectetur adipiscing elit"""
Numbers
x = 1 # Integer
y = 2.8 # Float
z = 1j # Complex number
# Display the type of variable x
print(type(x)) # Output: <class 'int'>
Booleans
is_active = True # Set the status to active
is_active = False # Set the status to inactive
# Evaluate truthiness of values
print(bool(0)) # Output: False (0 is considered False)
print(bool(1)) # Output: True (any non-zero value is considered True)
Lists
fruits = ["apple", "banana", "cherry"] # A list of fruit names
boolean_values = [True, False, False] # A list of boolean values
numbers = [1, 5, 7, 9, 3] # A list of integers
number_tuple_as_list = list((1, 5, 7, 9, 3)) # Convert a tuple to a list
Tuple
coordinates = (1, 2, 3) # A tuple representing coordinates
coordinates_from_tuple = tuple((1, 2, 3)) # Creating a tuple from a tuple
Set
unique_chars = {"a", "b", "c"} # A set containing unique characters
unique_chars_from_set = set(("a", "b", "c")) # Creating a set from a tuple of characters
Dictionary
# Creating an empty dictionary
empty_dict = {}
# Defining a dictionary with key-value pairs
my_dict = {"one": 1, "two": 2, "three": 3}
# Accessing the value associated with the key "one"
print(my_dict["one"]) # Output: 1
# Retrieving all keys in the dictionary
print(my_dict.keys()) # Output: dict_keys(['one', 'two', 'three'])
# Retrieving all values in the dictionary
print(my_dict.values()) # Output: dict_values([1, 2, 3])
# Updating the dictionary by adding a new key-value pair
my_dict.update({"four": 4})
# Retrieving all keys after the update
print(my_dict.keys()) # Output: dict_keys(['one', 'two', 'three', 'four'])
# Accessing the value associated with the newly added key "four"
print(my_dict['four']) # Output: 4
# Key: Value pairs, similar to a JSON object
Casting
# Creating integers from various data types
x = int(1) # x is assigned the value 1
y = int(2.8) # y is converted to 2
z = int("3") # z is converted from string to 3
# Creating floats from different data types
x = float(1) # x becomes 1.0
y = float(2.8) # y remains 2.8
z = float("3") # z is converted to 3.0
w = float("4.2") # w is converted to 4.2
# Creating strings from various data types
x = str("s1") # x is the string 's1'
y = str(2) # y becomes the string '2'
z = str(3.0) # z becomes the string '3.0'
Python Advanced Data Types
Heaps
import heapq
dataList = [12, 8, 7, 3, 6, 4]
heapq.heapify(dataList) # convert dataList into a Min Heap
print(dataList) # => [3, 4, 7, 12, 6, 8]
print(dataList[0]) # the smallest value is always at the root of the heap
heapq.heappush(dataList, 15) # add 15 to the heap
smallest = heapq.heappop(dataList) # remove and return the smallest element
print(smallest) # => 3
# Invert values to utilize Min Heap as Max Heap
dataList = [12, 8, 7, 3, 6, 4]
dataList = [-number for number in dataList] # negate values
heapq.heapify(dataList)
largest = heapq.heappop(dataList)
print(-largest) # => 12 (negate again to get original value)
# Heaps are binary trees where each parent node has a value less than or equal to its children.
# This structure is efficient for quickly retrieving minimum or maximum values.
# Time complexity: O(n) for heapify, O(log n) for push and pop operations.
See: Heapq
Stacks and Queues
from collections import deque
queue = deque() # initialize an empty deque
queue = deque([5, 6, 7]) # initialize with elements
queue.append(8) # add to the right end
queue.appendleft(4) # add to the left end
print(queue) # => deque([4, 5, 6, 7, 8])
removed_right = queue.pop() # remove & return from the right end
removed_left = queue.popleft() # remove & return from the left end
print(removed_right) # => 8
print(removed_left) # => 4
print(queue) # => deque([5, 6, 7])
queue.rotate(-1) # rotate 1 step to the left
print(queue) # => deque([6, 7, 5])
# A deque (double-ended queue) allows O(1) time complexity for appending or popping elements from either end.
# It can be effectively used as both a stack and a queue.
# Reference: Deque
Python Strings
Array-like
greeting = "Greetings, Universe"
print(greeting[2]) # Output: e
print(greeting[-2]) # Output: v
# Access the character at index 2 or the second-to-last character.
Looping
>>> for letter in "bar":
... print(letter)
b
a
r
# Iterate through each character in the word "bar".
Slicing string
┌───┬───┬───┬───┬───┬───┐
| a | p | p | l | e | s |
└───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 -7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'apples'
>>> s[1:4]
'ppl'
>>> s[0:1]
'a'
>>> s = 'apples'
>>> s[:1]
'a'
>>> s[1:]
'ples'
>>> s[:1] + s[1:]
'apples'
>>> s[:]
'apples'
>>> s = 'apples'
>>> s[-6:-1]
'appl'
>>> s[1:5]
'appl'
With a stride
>>> s = 'abcdef' * 3
>>> s
'abcdefabcdefabcdef'
>>> s[::3]
'abc'
>>> s[2::3]
'cfc'
>>> s[::-3]
'fed'
>>> s[::-1]
'fedcbafedcbafedcba'
String Length
>>> message = "Python Programming!"
>>> print(len(message))
21
# The len() function returns the number of characters in a string.
Multiple copies
>>> pattern = '**-'
>>> repetitions = 5
>>> pattern * repetitions
'**-**-**-**-**-'
Check String
>>> keyword = 'eggs'
>>> keyword in 'I love cooking with eggs!'
True
>>> keyword not in 'I prefer bacon for breakfast.'
True
Concatenates
>>> first = 'hello'
>>> second = 'world'
>>> first + second
'helloworld'
>>> 'hello' 'world'
'helloworld'
Formatting
person_name = "Alice"
print("Greetings, %s!" % person_name)
person_name = "Alice"
person_age = 30
print("%s is %d years old." % (person_name, person_age))
# Using format() Method
text1 = "I am {name}, and I love {hobby}.".format(name="Alice", hobby="painting")
text2 = "I am {0}, and I enjoy {1}.".format("Alice", "painting")
text3 = "I am {}, and I like {}.".format("Alice", "painting")
Input
>>> age = input("Enter your age: ")
Enter your age: 25
>>> age
'25'
# Retrieve input data from the console.
Join
>>> ", ".join(["Apple", "Banana", "Cherry"])
'Apple, Banana, Cherry'
Endswith
>>> "Python programming is fun.".endswith("fun.")
True
Python F-Strings (Since Python 3.6+)
f-Strings usage
>>> site = 'OpenAI.com'
>>> f"Welcome to {site}"
"Welcome to OpenAI.com"
>>> value = 15
>>> f'{value} multiplied by 2 equals {value * 2}'
'15 multiplied by 2 equals 30'
>>> f"""She exclaimed {"I'm excited!"}"""
'She exclaimed I'm excited!'
>>> f'3 {"{math}"}'
'3 {math}'
>>> f'{{3}} {"math"}'
'{3} math'
>>> user = 'Alice'
>>> years = 30
>>> f"""Greetings!
... My name is {user}.
... I am {years} years old."""
"Greetings!n My name is Alice.n I am 30 years old."
# This feature has been available since Python 3.6; refer to: Formatted string literals
f-Strings Fill Align
>>> f'{"example":15}' # [width]
'example '
>>> f'{"example":#>15}' # fill left
'##########example'
>>> f'{"example":_<15}' # fill right
'example______'
>>> f'{"example":^15}' # fill center
'----example----'
>>> f'{678:0<10}' # fill with numbers
'6780000000'
f-Strings Type
>>> f'{15:b}' # binary type
'1111'
>>> f'{15:o}' # octal type
'17'
>>> f'{255:x}' # hexadecimal type
'ff'
>>> f'{255:X}'
'FF'
>>> f'{123456789:e}' # scientific notation
'1.234568e+08'
>>> f'{70:c}' # character type
'F'
>>> f'{15:#b}' # [type] with notation (base)
'0b1111'
>>> f'{15:#o}'
'0o17'
>>> f'{15:#x}'
'0xf'
F-Strings Others
>>> f'{-6789:0=10}' # negative numbers
'-00006789'
>>> f'{6789:010}' # [0] shortcut (no align)
'0000006789'
>>> f'{-6789:010}'
'-000006789'
>>> import math # [.precision]
>>> math.e
2.718281828459045
>>> f'{math.e:.3f}'
'2.718'
>>> f'{5000000:,.2f}' # [grouping_option]
'5,000,000.00'
>>> f'{5000000:_.2f}'
'5_000_000.00'
>>> f'{0.75:0%}' # percentage
'75.000000%'
>>> f'{0.75:.0%}'
'75%'
F-Strings Sign
>>> f'{6789:+}' # [sign] (+/-)
'+6789'
>>> f'{-6789:+}'
'-6789'
>>> f'{-6789:+10}'
' -6789'
>>> f'{-6789:+010}'
'-00006789'
Python Lists
Defining
>>> list1 = []
>>> list1
[]
>>> list2 = [7, 8, 9]
>>> list2
[7, 8, 9]
>>> list3 = list((4, 5, 6))
>>> list3
[4, 5, 6]
>>> list4 = list(range(5, 16))
>>> list4
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Generate
>>> list(filter(lambda x: x % 2 == 0, range(1, 20)))
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [x ** 3 for x in range(1, 6) if x % 2 == 0]
[8, 64]
>>> [x for x in [1, 2, 3, 4, 5] if x < 3]
[1, 2]
>>> list(filter(lambda x: x < 3, [1, 2, 3, 4, 5]))
[1, 2]
Append
>>> numbers = []
>>> numbers.append(10)
>>> numbers
[10]
>>> numbers.append(20)
>>> numbers
[10, 20]
>>> numbers.append(40)
>>> numbers
[10, 20, 40]
>>> numbers.append(30)
>>> numbers
[10, 20, 40, 30]
List Slicing
# Syntax of list slicing:
# a_list[start:end]
# a_list[start:end:step]
# Slicing
>>> fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
>>> fruits[1:4]
['banana', 'cherry', 'date']
>>> fruits[-4:-1]
['banana', 'cherry', 'date']
>>> fruits[0:3]
['apple', 'banana', 'cherry']
# Omitting index
>>> fruits[:3]
['apple', 'banana', 'cherry']
>>> fruits[0:3]
['apple', 'banana', 'cherry']
>>> fruits[2:]
['cherry', 'date', 'fig', 'grape']
>>> fruits[2:len(fruits)]
['cherry', 'date', 'fig', 'grape']
>>> fruits
['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
>>> fruits[:]
['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
# With a stride
['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
>>> fruits[0:6:2]
['apple', 'cherry', 'fig']
>>> fruits[1:6:2]
['banana', 'date', 'grape']
>>> fruits[6:0:-2]
['grape', 'date', 'banana']
>>> fruits
['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
>>> fruits[::-1]
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
Remove
>>> items = ['apple', 'orange', 'banana']
>>> items.pop()
'banana'
>>> items
['apple', 'orange']
>>> del items[0]
>>> items
['orange']
Access
>>> letters = ['w', 'x', 'y', 'z']
>>> letters[0]
'w'
>>> letters[-1]
'z'
>>> letters[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Concatenating
>>> even = [2, 4, 6]
>>> even.extend([8, 10, 12])
>>> even
[2, 4, 6, 8, 10, 12]
>>> even = [2, 4, 6]
>>> even + [8, 10, 12]
[2, 4, 6, 8, 10, 12]
Sort & Reverse
>>> numbers = [7, 2, 9, 1, 4]
>>> numbers.sort()
>>> numbers
[1, 2, 4, 7, 9]
>>> numbers.reverse()
>>> numbers
[9, 7, 4, 2, 1]
Count
>>> numbers = [4, 2, 4, 1, 4]
>>> numbers.count(4)
3
Repeating
>>> items = ["go"] * 4
>>> items
['go', 'go', 'go', 'go']
Python Flow control
Basic
value = 8
if value > 10:
print("value is definitely greater than 10.")
elif value < 10:
print("value is less than 10.")
else:
print("value is exactly 10.")
One line
>>> x = 15
>>> y = 30
>>> result = "x" if x > y else "y"
>>> print(result)
y
else if
flag = False
if not flag:
print("Flag is False")
elif flag is None:
print("Flag is None")
else:
print("Flag is True")
Python Loops
Basic
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Prints: apple banana cherry
With index
colors = ["red", "green", "blue"]
# enumerate() adds a counter to an iterable
for index, color in enumerate(colors):
print(index, color)
# Prints: 0 red 1 green 2 blue
While
y = 0
while y < 5:
print(y)
y += 1 # Shorthand for y = y + 1
# Prints: 0 1 2 3 4
Break
y = 0
for index in range(7):
y = index * 5
if index == 4:
break
print(y)
# Prints: 0 5 10 15
Continue
for index in range(2, 6):
y = index * 5
if index == 4:
continue
print(y)
# Prints: 10 15 25
Range
for j in range(3):
print(j) # Prints: 0 1 2
for j in range(5, 9):
print(j) # Prints: 5 6 7 8
for j in range(5, 12, 3):
print(j) # Prints: 5 8 11
With zip()
days = ['Sun', 'Mon', 'Tue']
values = [10, 20, 30]
# Use zip to pack into a tuple list
for day, value in zip(days, values):
print('%d:%s, ' % (value, day))
# Prints: 10:Sun, 20:Mon, 30:Tue,
for/else
values = [45, 80, 150, 25, 60]
for v in values:
if v > 100:
print("%d is greater than 100" % v)
break
else:
print("No values greater than 100 found!")
See: Python Tips
Python Functions
Basic
def greet_user(name):
print(f'Hello, {name}!')
Return
def multiply(a, b):
print("a is %s, b is %s" % (a, b))
return a * b
result = multiply(4, 7) # => 28
Positional arguments
def collect_items(*items):
return items
result = collect_items('apple', 'banana', 'cherry') # => ('apple', 'banana', 'cherry')
Keyword arguments
def user_info(**info):
return info
# => {"name": "Alice", "age": 30}
result = user_info(name="Alice", age=30)
Returning multiple
def switch(a, b):
return b, a
a = 'first'
b = 'second'
a, b = switch(a, b) # => a = 'second', b = 'first'
Default Value
def concatenate(s, suffix=" world"):
return s + suffix
print(concatenate("Hello")) # => "Hello world"
print(concatenate("Hello", " everyone!")) # => "Hello everyone!"
Anonymous functions
# => True
(lambda s: 'a' in s)('apple')
# => 9
(lambda x: x * 3)(3)
Python Modules
Import modules
import math
print(math.factorial(5)) # => 120
From a module
from math import gcd, radians
print(gcd(48, 18)) # => 6
print(radians(180)) # => 3.141592653589793
Import all
from math import *
Shorten module
import math as m
# => True
math.factorial(5) == m.factorial(5)
Functions and attributes
import math
dir(math)
Python File Handling
Read file
# Reading a file line by line
with open("datafile.txt") as file:
for line in file:
print(line)
# Reading with line numbers
file = open("datafile.txt", "r")
for index, line in enumerate(file, start=1):
print("Line %s: %s" % (index, line))
String
# Writing a dictionary as a string to a file
data = {"x": 34, "y": 56}
with open("datafile1.txt", "w+") as file:
file.write(str(data))
# Reading the string back from the file
with open("datafile1.txt", "r+") as file:
data_read = file.read()
print(data_read)
Object
import json
# Writing a dictionary as a JSON object to a file
data = {"x": 34, "y": 56}
with open("datafile2.txt", "w+") as file:
file.write(json.dumps(data))
# Reading the JSON object back from the file
with open("datafile2.txt", "r+") as file:
data_read = json.load(file)
print(data_read)
Delete a File
import os
# Deleting a file if it exists
filename = "examplefile.txt"
if os.path.exists(filename):
os.remove(filename)
print(f"{filename} has been deleted.")
else:
print(f"{filename} does not exist.")
Check and Delete
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
print("File deleted successfully.")
else:
print("The file does not exist.")
Delete Folder
import os
os.rmdir("myfolder")
//For deleting non-empty directories, use shutil.rmtree() instead:
import shutil
shutil.rmtree("myfolder")
Python Classes & Inheritance
Defining
class MyNewClass:
pass
# Class Instantiation
my = MyNewClass()
Constructors
class Animal:
def __init__(self, sound):
self.sound = sound
# Creating instances of the Animal class
cat = Animal('Purr')
print(cat.sound) # Output: Purr
dog = Animal('Bark')
print(dog.sound) # Output: Bark
Method
class Dog:
# Method of the class
def bark(self):
print("Woof-Woof")
# Creating an instance of the Dog class
buddy = Dog()
# Calling the bark method
buddy.bark() # Output: "Woof-Woof"
Class Variables
class MyClass:
class_variable = "A class variable!"
# Accessing class variable directly from the class
print(MyClass.class_variable) # Output: A class variable!
# Creating an instance of MyClass
x = MyClass()
# Accessing class variable through the instance
print(x.class_variable) # Output: A class variable!
Super() Function
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's print_test() using super()
super().print_test()
# Creating an instance of ChildClass
child_instance = ChildClass()
# Calling the overridden method print_test()
child_instance.print_test()
# Output:
# Child Method
# Parent Method
repr() method
class Employee:
def __init__(self, name):
self.name = name
# The __repr__ method defines how the object will be represented as a string
def __repr__(self):
return self.name
# Creating an instance of Employee with the name 'John'
john = Employee('John')
# Printing the instance will call the __repr__ method
print(john) # => John
User-defined exceptions
class CustomError(Exception):
# Custom exception class inheriting from the base Exception class
pass
# Example usage
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(f"Caught an error: {e}")
Polymorphism
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
Overriding
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self() # => Child
Inheritance
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => Yoki
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
Miscellaneous
Generators
def double_numbers(iterable):
for number in iterable:
yield number * 2
Generator to list
values = (-x for x in [1, 2, 3, 4, 5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
Handle exceptions
try:
# Raise an IndexError to simulate an error
raise IndexError("This is an index error")
except IndexError as e:
pass # No operation here, but typically you'd handle the exception
except (TypeError, NameError):
pass # Handle multiple exceptions together if needed
else:
# This block runs only if no exception is raised in try
print("All good!")
finally:
# This block runs regardless of whether an exception occurred
print("We can clean up resources here")
Comments