Python ยท beginner reference
Python cheat sheet you can run.
The twelve things beginners use most, each with an example. Press Run, change the code, press Run again.
Printing and comments
print() shows things on the screen. A comment starts with #; Python ignores it, so use it to explain your code.
print("Hello, world!")
print("Add", 2 + 3)
print("a", "b", "c", sep="-")
print("no new line", end="")
print(" ...continued")
# this line is a comment and does nothingHello, world! Add 5 a-b-c no new line ...continued
Variables and types
A variable is a name for a value. The main types are whole numbers (int), decimals (float), text (str) and True/False (bool).
age = 12
price = 4.5
name = "Mia"
is_student = True
print(age, price, name, is_student)
print(type(age), type(price), type(name), type(is_student))
x = y = 0
a, b = 3, 4
a, b = b, a
print(x, y, a, b)12 4.5 Mia True <class 'int'> <class 'float'> <class 'str'> <class 'bool'> 0 0 4 3
Numbers and operators
Python is a calculator. Note that / always gives a decimal, // divides and rounds down, % gives the remainder and ** is a power.
print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2, 7 // 2, 7 % 2)
print(2 ** 10)
print(abs(-5), round(3.14159, 2), max(4, 9), min(4, 9))
print(divmod(17, 5))
print(int("42") + 1, float("2.5") * 2, str(99) + "!")9 5 14 3.5 3 1 1024 5 3.14 9 4 (3, 2) 43 5.0 99!
Strings
Text goes in quotes. Strings have many built-in methods, and an f-string puts values inside text.
word = "Python"
print(len(word), word[0], word[-1], word[1:4])
print(word.upper(), word.lower(), word.replace("P", "J"))
print("fun" in "Python is fun", "a,b,c".split(","))
print("-".join(["red", "green", "blue"]))
score = 9
print(f"Score: {score}/10 = {score / 10:.0%}")
print(" trim me ".strip(), "ha" * 3)6 P n yth PYTHON python Jython True ['a', 'b', 'c'] red-green-blue Score: 9/10 = 90% trim me hahaha
Lists
A list holds many values in order, in square brackets. You can change a list after you make it.
nums = [5, 3, 8, 1]
nums.append(7)
nums.insert(0, 10)
print(nums, len(nums))
print(nums[0], nums[-1], nums[1:3])
nums.remove(8)
nums.sort()
print(nums)
print(sum(nums), min(nums), max(nums))
print(sorted(nums, reverse=True))[10, 5, 3, 8, 1, 7] 6 10 7 [5, 3] [1, 3, 5, 7, 10] 26 1 10 [10, 7, 5, 3, 1]
Dictionaries, tuples and sets
A dictionary pairs keys with values. A tuple is a list that cannot change. A set keeps each value once.
ages = {"Asha": 10, "Ravi": 12}
ages["Meera"] = 9
print(ages["Asha"], len(ages))
for name, age in ages.items():
print(name, "is", age)
print("Ravi" in ages, ages.get("Zoe", "unknown"))
point = (3, 4)
x, y = point
print(x, y)
letters = set("mississippi")
print(sorted(letters), len(letters))10 3 Asha is 10 Ravi is 12 Meera is 9 True unknown 3 4 ['i', 'm', 'p', 's'] 4
If, elif and else
Conditions make choices. Indent the lines that belong to each branch. Compare with ==, !=, <, >, <=, >= and combine with and, or, not.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("Keep going")
age = 11
print(age > 8 and age < 13, not age == 11)
print("pass" if score >= 40 else "fail")B True False pass
Loops
A for loop repeats for each item. A while loop repeats while a condition is true. break leaves a loop and continue skips to the next round.
for i in range(3):
print("round", i)
for fruit in ["apple", "banana"]:
print(fruit)
n = 1
while n < 100:
n = n * 2
print(n)
for i in range(10):
if i == 2:
continue
if i == 5:
break
print(i, end=" ")
print()
for i, letter in enumerate("abc"):
print(i, letter)round 0 round 1 round 2 apple banana 128 0 1 3 4 0 a 1 b 2 c
Functions
A function is a named set of instructions. def defines it, parameters go in brackets and return sends back a value.
def area(width, height=1):
return width * height
print(area(3, 4), area(5))
double = lambda x: x * 2
print(double(21))
def greet(name):
print("Hi,", name)
greet("Sam")
print(sorted(["pear", "fig", "apple"], key=len))12 5 42 Hi, Sam ['fig', 'pear', 'apple']
List comprehensions
A list comprehension builds a list in one line: [what for item in group if condition].
squares = [n * n for n in range(1, 6)]
print(squares)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)
words = ["tree", "sun", "moon"]
print([w.upper() for w in words])
print({w: len(w) for w in words})
print(list(zip(["a", "b"], [1, 2])))[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
['TREE', 'SUN', 'MOON']
{'tree': 4, 'sun': 3, 'moon': 4}
[('a', 1), ('b', 2)]
Errors and try / except
Errors are normal. try and except let your program handle one without crashing.
try:
print(10 / 0)
except ZeroDivisionError:
print("You cannot divide by zero")
try:
number = int("abc")
except ValueError:
print("That is not a number")
print("The program keeps running")You cannot divide by zero That is not a number The program keeps running
The math module
Python's math module has many functions for maths. Use import math first.
import math
print(math.sqrt(144), math.pi)
print(math.floor(3.7), math.ceil(3.2))
print(math.factorial(5), math.gcd(12, 18))
print(round(math.sin(math.radians(30)), 2))12.0 3.141592653589793 3 4 120 6 0.5
Next steps
- Try a beginner program and change one line at a time.
- Read how to debug Python when something goes wrong.
- Look up a word in the coding glossary.
- Play Code Jungle or Python practice.
FAQ
Cheat sheet questions
What is a Python cheat sheet?
A short summary of the most used Python ideas with a small example of each. Keep it open while you write programs.
Can I run the examples?
Yes. Each example has a Run button on the page. Change the code and run it again to see what happens.
Is this Python 3?
Yes. The examples work the same in real Python 3, and the site checks that every example prints exactly what real Python prints.
What should I learn after the cheat sheet?
Try the beginner Python programs, then play the coding games. Practise by changing programs rather than just reading them.
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay