Skip to content

Python

Python
  • Python 2 is no longer supported (as of January 1, 2020)
  • Python 3 is the latest version (as of 2023)
  • Python 3 is the recommended version for new projects

create python virtual environemnt

python3 -m venv env
source env/bin/activate

install packages

pip install -r requirements.txt
pip freeze > requirements.txt

Python Basics

False, True, no x++, use x += 1

  • .py file extension
  • Indentation is significant (4 spaces or 1 tab)
  • Use # for comments
  • Use """ for docstrings
  • Use __init__ for constructors
  • Use __str__ for string representation
  • Use __repr__ for official string representation
  • Use __name__ for module name
  • Use __main__ for main module
  • to exit, use exit() or quit()
  • input() to pause the program and wait for user input
  • print() to print to the console
  • if you mix space and tab, you will get an IndentationError

Reserved Keywords

Keyword Keyword Keyword Keyword
False None True and
as assert async await
break class continue def
del elif else except
finally for from global
if import in is
lambda nonlocal not or
pass raise return try
while with yield

DataType Declaration

Although Python is dynamically typed, you can use type hints to indicate the expected type of a variable.

a: int = 5
b: float = 5.0
c: str = "Hello"
d: bool = True
e: list = [1, 2, 3]
f: tuple = (1, 2, 3)
g: dict = {"key": "value"}
h: set = {1, 2, 3}
# function with type hints
def add(a: int, b: int) -> int:
    return a + b