Nexus Learn

Python Cheat Sheet

The Python syntax you will use most, with a short example for each. Python uses indentation (four spaces) to show which lines belong together.

Variables and types

CommandWhat it does
x = 5Whole number (int). No type declaration needed.
y = 3.14Decimal number (float).
name = 'Ali'Text (str). Single or double quotes both work.
ok = TrueTrue or False (bool).
type(x)Tell what type a value is.
int('42'), str(42), float('1.5')Convert between types.
print(name, x)Show values on the screen.
age = int(input('Age: '))Ask the user to type something.

Strings

CommandWhat it does
len(s)Number of characters.
s.upper(), s.lower()Change the case.
s.strip()Remove spaces from both ends.
s.split(',')Cut a string into a list at each comma.
', '.join(items)Join a list of strings into one string.
s[0], s[-1], s[1:4]First character, last character, and a slice.
f'Hello {name}, you are {age}'Put values inside text (f-string).

Lists

CommandWhat it does
nums = [3, 1, 2]Make a list.
nums.append(4)Add to the end.
nums.insert(0, 9)Add at a position.
nums.remove(1)Remove the first matching value.
nums.pop()Remove and return the last item.
nums.sort()Sort in place. sorted(nums) gives a new sorted list.
len(nums), sum(nums), max(nums)Size, total and biggest.
3 in numsCheck if a value is in the list.

Dictionaries and sets

CommandWhat it does
d = {'a': 1, 'b': 2}Make a dictionary of key and value pairs.
d['a']Get a value. It raises an error if the key is missing.
d.get('z', 0)Get a value, or 0 if the key is missing.
d['c'] = 3Add or change an entry.
for k, v in d.items():Loop over keys and values.
s = {1, 2, 2, 3}A set keeps only unique values.
a | b, a & b, a - bUnion, intersection and difference of sets.

Decisions and loops

CommandWhat it does
if x > 5: / elif x == 5: / else:Choose between paths.
for i in range(5):Repeat 5 times, i = 0 to 4.
for item in nums:Visit every item in a list.
while x > 0:Repeat while a condition is true.
break / continueLeave the loop, or skip to the next round.
for i, v in enumerate(nums):Get the position and value together.

Functions

CommandWhat it does
def add(a, b=0):Define a function. b has a default value.
return a + bSend a result back.
lambda x: x * 2A tiny one-line function with no name.
def total(*args, **kwargs):Accept any number of values and named values.

Files and errors

CommandWhat it does
with open('a.txt') as f:Open a file and close it automatically.
text = f.read()Read the whole file.
open('a.txt', 'w')Open for writing. 'a' appends, 'r' reads.
try: / except ValueError: / finally:Catch an error so the program keeps running.
raise ValueError('bad input')Cause an error on purpose.

Comprehensions and classes

CommandWhat it does
[x * x for x in range(5)]Build a list in one line.
[x for x in nums if x > 1]Build a list with a filter.
{k: v for k, v in pairs}Build a dictionary in one line.
class Dog:Define a class.
def __init__(self, name):The constructor. self is the object itself.
class Puppy(Dog):Inheritance: Puppy gets everything Dog has.

Common beginner mistakes

Mixing tabs and spaces, forgetting the colon after if, for, while and def, using = (assign) instead of == (compare), and changing a list while looping over it.

Frequently asked questions

What is the difference between a list and a tuple?

A list can be changed after it is made. A tuple cannot. Use a tuple for values that should stay fixed.

What is the difference between == and is?

== checks if two values are equal. is checks if two names point to the very same object.

How do I read a number from the user?

input() always gives text. Wrap it in int() or float(), for example int(input('Age: ')).

Test yourself: practice questions on this topic. More cheat sheets: SQL Cheat Sheet · Git Cheat Sheet · Linux Commands Cheat Sheet · Big-O cheat sheet