Naming
var_names # snake_case
CONSTANT_VAR # UPPERCASE
ClassNames # PascalCase
_protected_class_attribute # single underscore
__private_class_attribute # double underscore
Data types
name = "Alice" # string (text)
age = 25 # int (whole nums)
height = 5.5 # float (decimal nums)
is_true = True # bool (True/False)
fruits = ["apple", "banana"] # list
person = { "name": "Alice", "age": 25 } # dict
Type Checking
x = 5
type(x) # int
Lists
fruits = ["apple", "banana"]
fruits[0] # get
fruits.append("cherry") # add
fruits.remove("banana") # remove
for fruit in fruits: # loop
print(fruit)
Dictionaries
person = { "name": "Alice", "age": 25 }
person["name"] # get
person["city"] = "New York" # add
person.pop("age", None) # remove
for key, value in person.items(): # loop
print(key, value)
Formatting
Concatenation
username = "Alex"
print("Welcome " + username) # Welcome Alex
f-strings
name = "Bob"
print(f"Thanks {name}") # Thanks Bob
Input
All input is returned as a string
name = input("Name: ")
height = int(input("Height: "))
Conditionals
Conditional statements include if, elif, and else
if temperature > 75:
print("Hot!")
elif temperature < 60:
print("Cold!")
else:
print("Mild")
Loops
For Loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # apple, banana, cherry
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for index, fruit in enumerate(fruits):
print(index, fruit) # 0 apple, 1 banana, 2 cherry
While Loops
while condition:
print("condition is True")
Loop Control
for i in range(10):
if i == 5:
break # exits out of loop
print(i) # 0, 1, 2, 3, 4
for i in range(5):
if i == 2:
continue # skips to next iteration
print(i) # 0, 1, 3, 4
Boolean Logic
Comparison Operators
== # equal to
!= # not equal to
> # greater than
< # less than
>= # greater or equal
<= # less or equal
Logical Operators
Logical operators include and, or, and not
if x > 0 and x < 10:
print("x is between 0 and 10")
if x < 0 or x > 10:
print("Outside range")
is_valid = not False
Functions
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Function Arguments
Different types of function arguments include: positional, default, keyword, arbitrary, and keyword arbitrary arguments
def area(width, height): # positional args
return width * height
area(5, 6) # must be passed in order
def area(width=5, height=5): # default args
return width * height
area() # default arg values 5, 5 are used
area(height=6, width=5) # keyword args can be passed in any order
def area(*args): # arbitrary args
return args[0] * args[1]
area(5, 6) # can pass any number of args
area(5, 6, 7, 8) # args[2] and args[3] are unused
def area(**kwargs): # arbitrary keyword args
return kwargs["width"] * kwargs["height"]
area(height=6, width=5) # can pass any number of keyword args in any order
area(width=5, potatos='round', height=6) # potatoes is unused
Built-in Functions
len("Hello") # length
type(123) # type check
int("42") # convert to int
float("3.14") # convert to float
str(123) # convert to string
round(3.14159, 2) # round
sum([1, 2, 3]) # sum
Scope
Determines the accessibility of variables, includes: local, enclosing, and global
x = 10 # global var
what_scope = "global"
def outer():
y = 20 # enclosing var
what_scope = "enclosing"
def inner():
z = 30 # local var
what_scope = "local"
print(x, y, z) # can access all higher scopes
print(what_scope) # local
inner()
print(x, y) # z doesnt exist in enclosing scope
print(what_scope) # enclosing
outer()
print(x) # y and z dont exist in global scope
print(what_scope) # global
Scope Modifiers
global
and nonlocal
can be used to modify the scope of variables
global_count = 0 # global var
def outer():
enclosing_count = 0 # enclosing var
global global_count # modifies global var
global_count += 1
def inner():
nonlocal enclosing_count
enclosing_count += 1 # modifies enclosing var
inner()
print(enclosing_count) # 1
outer()
print(global_count) # 1
Importing Modules
from math import sqrt # import a function
from random import * # import all functions
Error Handling
try:
# code that might raise an error
raise Exception("Error!")
except Exception as e:
print(e)
File I/O
r: read, w: write, a: append, x: create
file = open("file.txt", "r") # open file in read mode
content = file.read() # read file content
file.close() # close file