Python Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
x = 5- int. No type declaration needed.
pi = 3.14- float.
name = "Ada"- str. Single or double quotes both work.
ok = True- bool is True or False, capitalized.
nothing = None- the null value in Python.
type(x)- check a value's type at runtime.
Strings
f"Hi {name}, you are {age}"- f-string: inline any expression in {}.
s.upper() s.lower() s.strip()- case change and trim whitespace.
s.split(",")- split into a list on a separator.
", ".join(items)- join a list of strings back together.
s.replace("a", "b")- swap every occurrence.
s[0] s[-1] s[1:4]- index and slice. -1 is the last char.
Lists
nums = [1, 2, 3]- ordered, mutable.
nums.append(4)- add to the end.
nums.pop() nums.pop(0)- remove and return last, or by index.
len(nums)- count items.
nums[1:3] nums[::-1]- slice, and reverse with [::-1].
sorted(nums) nums.sort()- sorted() returns a copy, .sort() edits in place.
Dictionaries
user = {"name": "Ada", "age": 36}- key/value pairs.
user["name"]- read a value by key.
user.get("email", "n/a")- read with a fallback if the key is missing.
user["email"] = "[email protected]"- add or update a key.
user.keys() user.values() user.items()- iterate keys, values, or pairs.
"name" in user- check if a key exists.
Control flow
if x > 0: ... elif x == 0: ... else: ...- indentation defines blocks. Four spaces.
for item in items:- loop over any iterable.
for i in range(5):- 0, 1, 2, 3, 4.
while cond:- loop until cond is False.
break continue- exit the loop, or skip to the next pass.
for i, v in enumerate(items):- index and value together.
Functions
def add(a, b): return a + b- define and return.
def greet(name, greeting='Hi'):- default argument values.
def total(*args, **kwargs):- any number of positional / keyword args.
square = lambda n: n * n- small anonymous function.
add(2, b=3)- call positionally or by keyword.
Comprehensions
[n * 2 for n in nums]- build a list in one line.
[n for n in nums if n > 0]- filter while you build.
{k: v for k, v in pairs}- dict comprehension.
{n % 3 for n in nums}- set comprehension (unique values).
Unlock the full Python cheat sheet
You're seeing 2 of 7 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.