PYTHON
Cheat Sheet
codewithmosh.com
@moshhamedani
Primitive Types codewithmosh.com
Variables Escape sequences Numer functions
a = 1 (integer) \” round(x)
b = 1.1 (float) \’ abs(x)
c = 1 + 2j (complex) \\
d = “a” (string) \n
e = True (boolean) Type conversion
int(x)
Strings String methods float(x)
x = “Python” bool(x)
x.upper()
len(x) string(x)
x.lower()
x[0] x.title()
x[-1] x.strip()
x[0:3] x.find(“p”) Falsy values
x.replace(“a”, “b”) 0
“a” in x “”
Formatted strings None
name = f”{first} {last}”
Control Flow codewithmosh.com
Conditional statements Chaining comparison operators
if x == 1:
if 18 <= age < 65:
print(“a”)
elif x == 2:
print(“b”) For loops
else:
for n in range(1, 10):
print(“c”) …
While loops
Ternary operator
while n > 10:
x = “a” if n > 1 else “b”
…
Boolean operators Equality operators
x and y (both should be true) == (equal)
x or y (at least one true) != (not equal)
not x (inverses a boolean)
Functions codewithmosh.com
Defining functions Variable number of keyword arguments
def increment(number, by=1):
def save_user(**user):
return number + by …
save_user(id=1, name=“Mosh”)
Keyword arguments
increment(2, by=1)
Variable number of arguments
def multiply(*numbers):
for number in numbers:
print number
multiply(1, 2, 3, 4)
Shortcuts codewithmosh.com
DEBUGGING CODING (Windows) CODING (Mac)
Start Debugging F5 End of line End End of line fn+Right
Step Over F10 Beginning of line Home Beginning of line fn+Left
Step Into F11 End of file Ctrl+End End of file fn+Up
Step Out Shift+F11 Beginning of file Ctrl+Home Beginning of file fn+Down
Stop Debugging Shift+F5 Move line Alt+Up/Down Move line Alt+Up/Down
Duplicate line Shift+Alt+Down Duplicate line Shift+Alt+Down
Comment Ctrl+/ Comment Cmd+/
Lists codewithmosh.com
Creating lists Unpacking
letters = ["a", "b", "c"] first, second, *other = letters
matrix = [[0, 1], [1, 2]]
zeros = [0] * 5 Looping over lists
combined = zeros + letters
for letter in letters:
numbers = list(range(20))
...
Accessing items for index, letter in enumerate(letters):
letters = ["a", "b", "c", "d"] ...
letters[0] # "a"
letters[-1] # "d" Adding items
letters.append("e")
Slicing lists letters.insert(0, "-")
letters[0:3] # "a", "b", "c"
letters[:3] # "a", "b", "c" Removing items
letters[0:] # "a", "b", "c", "d"
letters.pop()
letters[:] # "a", "b", "c", "d" letters.pop(0)
letters[::2] # "a", "c"
letters.remove("b")
letters[::-1] # "d", "c", "b", "a"
del letters[0:3]
Lists codewithmosh.com
Finding items Zip function
if "f" in letters: list1 = [1, 2, 3]
letters.index("f") list2 = [10, 20, 30]
combined = list(zip(list1, list2))
Sorting lists # [(1, 10), (2, 20)]
letters.sort()
letters.sort(reverse=True) Unpacking operator
list1 = [1, 2, 3]
Custom sorting list2 = [10, 20, 30]
combined = [*list1, “a”, *list2]
items = [
("Product1", 10),
("Product2", 9),
("Product3", 11)
]
items.sort(key=lambda item: item[1])
Tuples, Sets, and Dictionaries codewithmosh.com
Tuples Sets
point = 1, 2, 3 first = {1, 2, 3, 4}
point = (1, 2, 3) second = {1, 5}
point = (1,)
point = () first | second # {1, 2, 3, 4, 5}
point(0:2) first & second # {1}
x, y, z = point first - second # {2, 3, 4}
if 10 in point: first ^ second # {2, 3, 4, 5}
…
Dictionaries
Swapping variables point = {"x": 1, "y": 2}
x = 10 point = dict(x=1, y=2)
y = 11 point["z"] = 3
x, y = y, x if "a" in point:
...
Arrays point.get("a", 0) # 0
del point["x"]
from array import array
for key, value in point.items():
numbers = array(“i”, [1, 2, 3])
...
Comprehensions codewithmosh.com
List comprehensions
values = [x * 2 for x in range(5)]
values = [x * 2 for x in range(5) if x % 2 == 0]
Set comprehensions
values = {x * 2 for x in range(5)}
Dictionary comprehensions
values = {x: x * 2 for x in range(5)}
Generator expressions
values = {x: x * 2 for x in range(500000)}
Exceptions codewithmosh.com
Handling Exceptions
try:
…
except (ValueError, ZeroDivisionError):
…
else:
# no exceptions raised
finally:
# cleanup code
Raising exceptions
if x < 1:
raise ValueError(“…”)
The with statement
with open(“file.txt”) as file:
…
Classes codewithmosh.com
Creating classes Instance vs class methods
class Point: class Point:
def __init__(self, x, y):
def draw(self):
self.x = x …
self.y = y
@classmethod
def draw(self):
def zero(cls):
… return cls(0, 0)
Instance vs class attributes
class Point: Magic methods
default_color = “red”
__str__()
__eq__()
def __init__(self, x, y):
__cmp__()
self.x = x
Classes codewithmosh.com
Private members Inheritance
class Point: class FileStream(Stream):
def __init__(self, x):
def open(self):
self.__x = x super().open()
…
Properties Multiple inheritance
class Point:
class FlyingFish(Flyer, Swimmer):
def __init__(self, x):
…
self.__x = x
@property Abstract base classes
def x(self): from abc import ABC, abstractmethod
return self.__x
class Stream(ABC):
@property.setter: @abstractmethod
def x.setter(self, value): def read(self):
self.__x = value pass
Classes codewithmosh.com
Named tuples
from collections import namedtuple
Point = namedtuple(“Point”, [“x”, “y”])
point = Point(x=1, y=2)