CodeStart / Python Course / Cheat Sheet

Python Cheat Sheet for Beginners

The most useful Python commands on one page. Lines starting with # are comments that show what each line does or returns. New to Python? Start with the free course.

Print and input

print("Hello, world!")
print("a", "b", sep="-")       # a-b
name = input("Your name? ")
age = int(input("Age? "))       # text to int
print(f"{name} is {age} years old")

Comments and variables

# This is a comment
x = 10            # int (whole number)
price = 9.99      # float (decimal number)
name = "Anna"     # str (text)
is_ok = True      # bool (True or False)
a, b = 1, 2       # assign two variables at once
print(type(x))    # <class 'int'>

Type conversion

int("42")        # 42
float("3.5")     # 3.5
str(100)         # "100"
bool(0)          # False

Math operators

7 + 2     # 9
7 - 2     # 5
7 * 2     # 14
7 / 2     # 3.5   (always a float)
7 // 2    # 3     (whole-number division)
7 % 2     # 1     (remainder)
2 ** 3    # 8     (power)
x = 5
x += 1    # same as x = x + 1

Comparisons and logic

x = 5
x == 5              # True  (equal)
x != 5              # False (not equal)
x > 3 and x < 10    # True
x < 3 or x > 10     # False
not (x == 5)        # False

Strings

s = "Hello, World!"
len(s)                          # 13
s[0]                            # "H"
s[-1]                           # "!"
s[0:5]                          # "Hello"
s.upper()                       # "HELLO, WORLD!"
s.lower()                       # "hello, world!"
s.replace("World", "Python")    # "Hello, Python!"
s.split(", ")                   # ["Hello", "World!"]
"  hi  ".strip()                # "hi"
"lo" in s                       # True

if, elif and else

age = 15
if age < 6:
    print("Free")
elif age < 18:
    print("Child ticket")
else:
    print("Adult ticket")

while loop

i = 0
while i < 3:
    print(i)
    i += 1          # without this the loop never ends

for loop and range()

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

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

for i in range(0, 10, 2):   # 0, 2, 4, 6, 8
    print(i)

# break leaves the loop, continue skips to the next round

Lists

nums = [3, 1, 2]
nums.append(4)       # add to the end
nums.insert(0, 9)    # insert at position 0
nums.remove(1)       # remove the value 1
nums.pop()           # remove and return the last item
nums.sort()          # sort in place
len(nums)            # number of items
nums[0]              # first item
nums[1:3]            # slice
3 in nums            # True or False
for n in nums:
    print(n)

Lists of lists (2D)

grid = [[1, 2, 3], [4, 5, 6]]
grid[1][2]                # 6  (row 1, column 2)
for row in grid:
    for value in row:
        print(value)

Functions

def add(a, b):
    return a + b

result = add(2, 3)            # 5

def greet(name="friend"):     # default value
    print(f"Hello, {name}!")

greet()                       # Hello, friend!

Classes and objects

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says Woof!")

rex = Dog("Rex")
rex.bark()                    # Rex says Woof!

Useful built-in functions

import random

len([1, 2, 3])          # 3
sum([1, 2, 3])          # 6
min(4, 2, 8)            # 2
max(4, 2, 8)            # 8
abs(-5)                 # 5
round(3.14159, 2)       # 3.14
sorted([3, 1, 2])       # [1, 2, 3]
random.randint(1, 6)    # random number from 1 to 6

Common Python errors

  • SyntaxError: A typo, a missing colon or an unclosed bracket or quote.
  • IndentationError: The spaces at the start of a line are wrong.
  • NameError: You used a variable that does not exist yet (or misspelled it).
  • TypeError: You mixed types that do not go together, for example "5" + 2.
  • ValueError: The value has the right type but cannot be used, for example int("abc").
  • IndexError: You asked for a list position that does not exist.
  • ZeroDivisionError: You divided a number by zero.