Skip to content

Python3 Notes & Cheatsheet

Packages and Builtin Functions

dir()
float()
int()
len()
list()
max()
min()
print()
round()
str()
type()
abs()
help()

Data Types

<class "int">
<class "float">
<class "str">

x = 3+5j
x.real
x.imag
a = 3
b = 5
c = complex(a, b)

y = bytearray(6)
z = memoryview(bytes(5))

Operators

a = []
b = []
a is b
### False
a == b
### True

Dates

from datetime import date as d
d.today()
str(d.today())

Lists

l.pop()
l.pop(4)
l.append(9)
l.remove(9)
l.count(1)
l.reverse()
l.sort()
len(l)
l[-len(l)]
l[1:3]
l[1:]
l[-1:]
### last one
l[:-1]
### except last one
9 in l
3 not in l
range(1,9,2)

Tuples

### can't be modified
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers[0]
numbers[-2]
numbers[:-3]
numbers.count(2)
numbers.index(2)

Dictionaries

dict_detail = {}
dict_detail["first name"] = "Rob"

person_details = dict(first_name="Rob", surname="Mastrodomenico",
    gender="Male", favourite_food="Pizza")
personal_details.clear()
personal_details.items()
list(personal_details.items())[0]
personal_details.keys()
personal_details.values()

x = ('key1', 'key2', 'key3')
y = 0
res = dict.fromkeys(x, y)

Sets

### storing unique values
names = {'Tony','Peter','Natasha','Wanda'}
names = set(('Tony','Peter','Natasha','Wanda', 1, 2, 3))
names = set(['Tony','Peter','Natasha','Wanda', 1, 2, 3])
names = set('Wanda')
names.add('Steve')

names.union(more_names)

names & more_names
names.intersection(more_names)
names & more_names & even_more_names

names - more_names
names.difference(more_names)
names - more_names - even_more_names
names.difference(more_names, even_more_names)

names ^ more_names
names.symmetric_difference(more_names)
names | more_names
names.isdisjoint(more_names)
names.issubset(more_names)
names.issuperset(more_names)

names.pop()
names.add('Bruce')
names.remove('Tony')
### if not exists, return KeyError
names.discard('Sue')
### always return True no matter key exists or not
names.clear()

frozen_names = frozenset({'Tony','Peter','Natasha','Wanda'})
### cannot be altered

Strings

single_quote_string = 'string with a \' single quote'
single_quote_string = """string with a ' single quote"""
raw_string = r"This has a \n in it"
not_raw_string = "This has a \n in it"
name.lower()
name.upper()
name.split(" ")
match_details.replace(",",":")
match_details = ','.join(details)

Regular Expressions

import re
re.findall("[a-m]", name)
### find specific character
re.findall("\d", txt)
re.findall("[0-9]", txt)
### find integer
re.findall("he..o", txt)
re.findall("^start", txt)
re.findall("end$", txt)
re.findall("aix*", txt)
### ai followed by 0 or more x
re.findall("aix+", txt)
### ai followed by one or more x
re.findall("mo{2}", txt)
re.findall("avengers|heroes", txt)
re.findall("\s", txt)
### find space
re.split("\s", txt, maxsplit=2)
re.sub("\s", "9", txt, 3)
re.search("ai", txt)
  • \A: “\AIt”
  • \b: at the beginning or at the end of a word
  • \B: NOT at the beginning (or at the end) of a word
  • \d: digits (numbers from 0-9)
  • \D: DOES NOT contain digits
  • \s: white space character
  • \S: DOES NOT contain a white space character
  • \w: any word characters (characters from a to Z, digits from 0-9, and the underscore _ character)
  • \W: DOES NOT contain any word characters

Variables and Data Types

Variables are used to store data in a program. Python3 supports several data types, including integers, floats, strings, and boolean values. Here are some examples of how to declare and initialize variables in Python3:

x = 5    # integer
y = 3.14 # float
name = "John" # string
is_active = True # boolean

In Python3, variables do not need to be declared before they are used, unlike other programming languages such as C or Java. This makes Python3 code shorter and more readable.

Control Flow Statements

Control flow statements are used to control the flow of execution in a program. Python3 supports several control flow statements, including if-else statements, loops, and switch statements. Here are some examples of how to use control flow statements in Python3:

# if-else statement
if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")

# for loop
for i in range(10):
    print(i)

# while loop
i = 0
while i < 10:
    print(i)
    i += 1

Python3 does not have a built-in switch statement, but it can be emulated with a dictionary.

Functions and Modules

Functions are reusable blocks of code that perform specific tasks. Modules are collections of functions that can be imported into a program. Python3 supports both functions and modules, and they can be used to organize and simplify code. Here are some examples of how to define functions and use modules in Python3:

# function definition
def add(x, y):
    return x + y

# module import
import math
print(math.sqrt(16))

In Python3, functions can have default argument values and can return multiple values. Modules can be used to import code from other files, making it easier to organize and reuse code.

Modern Python Libraries

  • Pydantic can be considered the core of this tech stack, serving as a Schema definition library. It can unify the parsing of configurations, the definition of later ORM queries, and the things like API definition, parameter validation, serialization, etc., reducing the trouble of manual conversion and greatly improving productivity.
  • FastAPI API framework, looks similar to flask, but is more feature-rich. It supports both synchronous and asynchronous, using Pydantic as the data model, and can automatically generate API documentation based on interface parameters.
  • SQLModel uses Pydantic for SQL database ORM schema definition and queries.
  • beanie If you use MongoDB, you can try this, which also uses Pydantic for definitions.
  • httpx The library for sending HTTP requests, supports both synchronous and asynchronous, to replace requests.
  • typer Command line parameter parsing library.
  • loguru feature-rich logging library, much easier to use than Python’s built-in one.
  • rich A library to optimize print output styles, making printing more beautiful and pleasing to the eye, very useful when debugging.
  • arrow Date and time library.
  • celery Task queue, for running some scheduled tasks or asynchronous background tasks, mainly supports Redis and RabbitMQ. This is also an antique, but there has never been a reliable alternative.
  • rq If the task is not very important, or if you don’t like the above celeryrq, and need a lightweight solution, try this one that only supports Redis.

Useful Tools

  • pyenv Python version management.
  • poetry Virtual environment and dependency library management, the usage experience is more like yarn on the nodejs side.
  • pipx Python tool management.

How to package a Python project into a single executable file

  • pyinstaller (https://github.com/pyinstaller/pyinstaller)
  • cx_Freeze (https://github.com/marcelotduarte/cx_Freeze)

Reading List

  • https://www.python.org/
  • https://superfastpython.com/asyncio-tcp-vs-unix-sockets/
  • The Python Book (Rob Mastrodomenico)
  • https://www.w3schools.com/python/
  • https://regexr.com
  • https://github.com/python
  • https://www.pythoncheatsheet.org/
Feedback