
I’ve created this Python 3.9 cheat sheet to help beginners learn the syntax of the Python Programming language
Variables
a = 23 # integerb = 23.3 # floatc = 2+ j # complex number (a + bi)d = "Hello" # stringe = True # boolean (True / False)
Strings
str = “Hello Python”len(str)str[0]str[-1]str[0:3]# Formatted stringsname = f”{first} {last}”# Escape sequences\” \’ \\ \n# String methodsstr.upper()str.lower()str.title()str.strip()str.find(“p”)str.replace(“a”, “b”)“a” in str
Type Conversion
int(a)float(a)bool(a)string(a)
Falsy Values
0“”[]
Conditional Statements
if num == 1:print(“1”)elif num == 2:print(“1”)else:print(“0”)# Ternary operatorx = “a” if n > 1 else “b”# Chaining comparison operators
if 18 <= age < 65:
Loops
for n in range(1, 10):print(n)while n < 10:print(n)n += 1
Functions
def increment(number, by=1):return number + by# Keyword argumentsincrement(2, by=1)# Variable number of argumentsdef multiply(*numbers):for number in numbers:print numbermultiply(1, 2, 3, 4)# Variable number of keyword argumentsdef save_user(**user):...save_user(id=1, name="Deep")
Lists
# Creating listsletters = ["a", "b", "c"]matrix = [[0, 1], [1, 2]]zeros = [0] * 5combined = zeros + lettersnumbers = list(range(20))# Accessing itemsletters = ["a", "b", "c", "d"]letters[0] # "a"letters[-1] # "d"# Slicing listsletters[0:3] # "a", "b", "c"letters[:3] # "a", "b", "c"letters[0:] # "a", "b", "c", "d"letters[:] # "a", "b", "c", "d"letters[::2] # "a", "c"letters[::-1] # "d", "c", "b", "a"# Unpackingfirst, second, *other = letters# Looping over listsfor letter in letters:...for index, letter in enumerate(letters):...# Adding itemsletters.append("e")letters.insert(0, "-")# Removing itemsletters.pop()letters.pop(0)letters.remove("b")del letters[0:3]# Finding itemsif "f" in letters:letters.index("f")# Sorting listsletters.sort()letters.sort(reverse=True)# Custom sortingitems = [("Product1", 10),("Product2", 9),("Product3", 11)]items.sort(key=lambda item: item[1])# Map and filterprices = list(map(lambda item: item[1], items))expensive_items = list(filter(lambda item: item[1] >= 10, items))# List comprehensionsprices = [item[1] for item in items]expensive_items = [item for item in items if item[1] >= 10]# Zip functionlist1 = [1, 2, 3]list2 = [10, 20, 30]combined = list(zip(list1, list2)) # [(1, 10), (2, 20)]
Tuples
point = (1, 2, 3)point(0:2) # (1, 2)x, y, z = pointif 10 in point:...# Swapping variablesx = 10y = 11x, y = y, x
Arrays
from array import arraynumbers = array("i", [1, 2, 3])
Sets
first = {1, 2, 3, 4}second = {1, 5}first | second # {1, 2, 3, 4, 5}first & second # {1}first - second # {2, 3, 4}first ^ second # {2, 3, 4, 5}if 1 in first:...
Dictionaries
point = {"x": 1, "y": 2}point = dict(x=1, y=2)point["z"] = 3if "a" in point:...point.get("a", 0) # 0del point["x"]for key, value in point.items():...# Dictionary comprehensionsvalues = {x: x * 2 for x in range(5)}
Generator Expressions
values = (x * 2 for x in range(10000))len(values) # Errorfor x in values:
Unpacking Operator
first = [1, 2, 3]second = [4, 5, 6]combined = [*first, "a", *second]first = {"x": 1}second = {"y": 2}combined = {**first, **second}
Exceptions
# Handling Exceptionstry:…except (ValueError, ZeroDivisionError):…else:# no exceptions raisedfinally:# cleanup code# Raising exceptionsif x < 1:raise ValueError(“…”)# The with statementwith open(“file.txt”) as file:…
Classes
# Creating classesclass Point:def __init__(self, x, y):self.x = xself.y = ydef draw(self):…# Instance vs class attributesclass Point:default_color = “red”def __init__(self, x, y):self.x = x# Instance vs class methodsclass Point:def draw(self):…@classmethoddef zero(cls):return cls(0, 0)# Magic methods__str__()__eq__()__cmp__()...# Private membersclass Point:def __init__(self, x):self.__x = x# Propertiesclass Point:def __init__(self, x):self.__x = x@propertydef x(self):return self.__x@property.setter:def x.setter(self, value):self.__x = value# Inheritanceclass FileStream(Stream):def open(self):super().open()…# Multiple inheritanceclass FlyingFish(Flyer, Swimmer):…# Abstract base classesfrom abc import ABC, abstractmethodclass Stream(ABC):@abstractmethoddef read(self):pass# Named tuplesfrom collections import namedtuplePoint = namedtuple(“Point”, [“x”, “y”])point = Point(x=1, y=2)