Python cheat sheet · BrainBit Infotech Teaching · brainbit-teaching.com/courses/python/notes/cheatsheet/
Basics
Output, input, comments
print("Hi", name, sep=" ", end="\n")
name = input("Name: ") # always a string
age = int(input("Age: ")) # convert to a number
# a comment
Data types
| Type | Example | Convert |
|---|---|---|
int | 25 | int("25") |
float | 3.5 | float("3.5") |
str | "hello" | str(25) |
bool | True, False | bool(0) is False |
type(x) tells you the type of x.
Operators
| Kind | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Compare | == != > < >= <= |
| Logical | and or not |
| Assign | = += -= *= /= |
7 // 2 is 3, 7 % 2 is 1, 2 ** 3 is 8. Order: (), **, * / // %, + -.
Strings
s = "Python"
s[0] # 'P' s[-1] # 'n'
s[0:3] # 'Pyt' s[::-1] # 'nohtyP'
len(s) # 6
s.upper() s.lower() s.strip() s.replace("P", "J")
"a,b,c".split(",") # ['a', 'b', 'c']
"-".join(["a", "b"]) # 'a-b'
f"{name} scored {marks:.1f}%"
Strings cannot be changed in place: methods return a new string.
Decisions
if marks >= 90:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
result = "Pass" if marks >= 33 else "Fail"
match day:
case "Sat" | "Sun":
print("Holiday")
case _:
print("School")
Loops
for i in range(1, 6): # 1 2 3 4 5
print(i)
for ch in "abc": ...
while n > 0:
n -= 1
range(stop), range(start, stop), range(start, stop, step): the stop is never included. break leaves the loop; continue skips to the next turn.
Collections
| List | Tuple | Set | Dict | |
|---|---|---|---|---|
| Write | [1, 2] | (1, 2) | {1, 2} | {"a": 1} |
| Ordered | yes | yes | no | yes (insertion) |
| Changeable | yes | no | yes | yes |
| Duplicates | yes | yes | no | keys no |
List
nums = [5, 3, 8]
nums.append(1); nums.insert(0, 9)
nums.remove(3); nums.pop()
nums.sort(); sorted(nums, reverse=True)
sum(nums); max(nums); len(nums)
copy = nums.copy() # b = a is NOT a copy
Dictionary
d = {"name": "Asha", "marks": 91}
d["city"] = "Ranchi" # add or update
d.get("age", 0) # no KeyError
for key, value in d.items(): ...
del d["city"]
Set
a | b # union a & b # common
a - b # difference
Functions
def area(length, width=1):
"""Return the area of a rectangle."""
return length * width
area(5, 2); area(length=5)
def total(*nums): return sum(nums)
square = lambda x: x * x
A variable made inside a function is local to it.
Files and errors
with open("notes.txt", "w") as f: # "r" read, "a" append
f.write("Hello\n")
with open("notes.txt") as f:
for line in f:
print(line.strip())
try:
n = int(input())
except ValueError as e:
print("Not a number:", e)
else:
print("OK")
finally:
print("Always runs")
Common errors: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError.
Classes
class Student:
school = "DPS" # class attribute
def __init__(self, name, marks):
self.name = name # instance attribute
self.marks = marks
def passed(self):
return self.marks >= 33
def __str__(self):
return f"{self.name}: {self.marks}"
class Monitor(Student): # inheritance
def __init__(self, name, marks, section):
super().__init__(name, marks)
self.section = section
Pythonic shortcuts
squares = [n * n for n in range(5)]
evens = [n for n in nums if n % 2 == 0]
for i, name in enumerate(names, start=1): ...
for n, m in zip(names, marks): ...
sorted(students, key=lambda s: s["marks"])
Modules
import math, random
from datetime import date
math.sqrt(16); random.randint(1, 6); date.today()
Install a package from a terminal: pip install requests.