ShareYourGroupShareYourGroupPython

Python cheat sheet for beginners

The core of the language on one page. It is a reminder for people who have done the lessons, not a replacement for them. Each heading links to the lesson that explains it. Print it or keep it open while you practise.

Output, input and variables

See lessons on print, variables and input.

print("Hello", name, sep=", ", end="\n")   # show values
name = input("Your name? ")                # always returns text
age = int(input("Age? "))                  # convert to a number
x, y = 5, 9                                # two variables at once
x += 1                                     # same as x = x + 1
# a comment: Python ignores this line

Types and conversion

TypeExampleConvert with
int42int("42")
float3.14float("3.14")
str"hello"str(42)
boolTrue, Falsebool(0)
list[1, 2, 3]list("abc")
tuple(1, 2)tuple([1, 2])
set{1, 2}set([1, 1, 2])
dict{"a": 1}dict(a=1)

Operators

KindOperators
Arithmetic+ - * / // (floor) % (remainder) ** (power)
Comparison== != < > <= >=
Logicand or not
Membershipin not in

See numbers and maths.

Strings

See strings and string methods.

s = "Hello, World"
print(len(s), s[0], s[-1], s[0:5], s[::-1])
print(s.upper(), s.lower(), s.replace("World", "India"))
print(s.split(", "), "-".join(["a", "b"]), "  hi ".strip())
print(s.find("World"), s.count("l"), s.startswith("He"), "lo" in s)
n = 3.14159
print(f"{s} has {len(s)} characters; pi is {n:.2f}")

Output

12 H d Hello dlroW ,olleH
HELLO, WORLD hello, world Hello, India
['Hello', 'World'] a-b hi
7 3 True True
Hello, World has 12 characters; pi is 3.14

Decisions

See if, elif and else.

marks = 68
if marks >= 75:
    grade = "A"
elif marks >= 50:
    grade = "B"
else:
    grade = "C"
print(grade, "pass" if marks >= 33 else "fail")

Output

B pass

Loops

See while loops and for loops.

for i in range(3):            # 0 1 2
    print(i, end=" ")
for i in range(2, 11, 4):     # 2 6 10
    print(i, end=" ")
print()
n = 3
while n > 0:
    n -= 1
    if n == 1:
        continue              # skip the rest of this round
    print("n is", n)
for number, name in enumerate(["Asha", "Ravi"], 1):
    print(number, name)

Output

0 1 2 2 6 10 
n is 2
n is 0
1 Asha
2 Ravi

break leaves a loop at once. continue jumps to the next round.

Lists

See lists and sorting and slicing.

a = [5, 2, 9]
a.append(7)            # add at the end
a.insert(0, 1)         # add at a position
a.remove(2)            # remove by value
last = a.pop()         # remove and return the last
a.sort()               # sort in place
print(a, last, len(a), sum(a), min(a), max(a))
print(sorted(a, reverse=True), a[:2], a[-1], 9 in a, a.index(9))
print([x * 2 for x in a if x > 1])

Output

[1, 5, 9] 7 3 15 1 9
[9, 5, 1] [1, 5] 9 True 2
[10, 18]

Tuples and sets

See tuples and sets.

point = (3, 5)
x, y = point
print(x, y)
s = {1, 2, 2, 3}
s.add(4)
print(sorted(s), sorted(s & {2, 4, 6}), sorted(s - {1}))

Output

3 5
[1, 2, 3, 4] [2, 4] [2, 3, 4]

Dictionaries

See dictionaries.

d = {"tea": 10, "lassi": 40}
d["samosa"] = 15                 # add or change
print(d["tea"], d.get("milk", 0), "tea" in d, len(d))
for key, value in d.items():
    print(key, value)
del d["tea"]
print(list(d.keys()), list(d.values()))

Output

10 0 True 3
tea 10
lassi 40
samosa 15
['lassi', 'samosa'] [40, 15]

Functions

See functions and arguments and scope.

def area(length, width=1):
    """Return the area of a rectangle."""
    return length * width

print(area(4, 5), area(4), area(width=2, length=3))

Output

20 4 6

Modules

See modules and import.

import math, random, datetime
random.seed(1)
print(math.sqrt(16), math.ceil(2.1), math.pi)
print(random.randint(1, 6), random.choice(["a", "b"]))
print(datetime.date(2026, 11, 12).strftime("%d %B %Y"))

Output

4.0 3 3.141592653589793
2 a
12 November 2026

Files

See reading and writing files.

with open("demo.txt", "w", encoding="utf-8") as f:   # "w" write, "a" append, "r" read
    f.write("line one\nline two\n")
with open("demo.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Output

line one
line two

Errors

See try and except and the error pages.

try:
    n = int("abc")
except ValueError:
    print("not a number")
else:
    print("ok", n)
finally:
    print("always runs")

Output

not a number
always runs

Classes

See classes and objects.

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def passed(self):
        return self.marks >= 33

s = Student("Asha", 78)
print(s.name, s.passed())

Output

Asha True

Five habits that prevent most beginner bugs

  1. Indent with four spaces, never tabs, and keep every line of a block level.
  2. Remember that input gives text. Convert before doing maths.
  3. Counting starts at 0, and the stop value of a range or slice is not included.
  4. = stores, == compares.
  5. Methods such as sort and append change the list and return None. Do not assign their result.

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.