1
Python
Python Basics:
print(arg) → print to console with argument
print(f{arg}) → print(f“hello world”)
# → used for comments
variable_name = value
Different types of data types:
string, integer, float (decimal points), bool (true or false)
typecasting: process of converting a variable from one data type to another
str(), int(), float(), bool()
type(var) → gives you the data type of the variable
input(prompt) → prompt gets printed to console and takes input
input() returns the entered data as a string, use typecasting
incrementation → num += 1, you can use + – * / all like this
raise to some power → num ** 3 or num **= 3
modulus → num % 2
round(var) or round(var, num) → rounds float to closest integer or to num decimal places
abs(var) → | var |
pow(var, power) → raise var to a given power
max(var1, var2, var3) → maximum between variables
min(var1,var2, var3) → minimum between variables
import math → how to import a module (math)
math.pi → pi’s value
math.e → euler’s constant value
math.sqrt(var) → sqrt function
math.ceil(var) → round up
math.floor(var) → round down
2
Conditionals:
var == num → == used to compare
if conditional statement:
# do this
elif conditional statement: → doesn’t run if any other if/elif runs
# do this
else:
# do this
logical operators:
and → all must be true
or → at least one must be true
not → invertsbool value
conditional expression → A one line shortcut for the if else statement (ternary operator)
var = “even” if num % 2 == 0 else “odd” → use cases
var = a if a > b else b → use cases
string methods:
len(var) → length of string
var.find(“value”) → returns the first occurrence of value in var else -1
indexing starts from 0
var.rfind(“value”) → returns the last occurrence of value in var else -1
var.capitalize() → first letter capitalized
var.upper() → return all to uppercase
var.lower() → return all to lowercase
var.isdigit() → return true if string only has digits
var.isalpha() → return true if string only has alphabets (not even symbols)
var.count(value) → counts the occurrences of value in var
var.replace(value, newValue) → replaces all occurrences of value in var to newValue
whole list for these methods print(help(str)) or look at the documentations
indexing → accessing elements of a sequence using [ ]
[start : end : step]
var = “1234–5678”
var[0:4] → “1234” ending index exclusive, starting inclusive
3
var[:4] → same thing as above
var [4:] → from 4th index to the end
var[-1] → last index, basically reverse order starting from -1
var[::2] → indexing with a step of 2
format specifiers → format a value based on flags
print(f “{value:.2f}) → 2 decimal points
print(f “{value:10}) → take 10 spaces
print(f “{value:010}) → take 10 spaces padding with 0s
print(f “{value:<10}) → left justified
print(f “{value:>10}) → right justified
print(f “{value:^10}) → center justified
print(f “{value:+}) → + signed or – signed according to value
print(f “{value:,}) → thousands separated by commas
print(f “{value:+,.2f}) → combinations of flags
while loop → execute some code while some condition remains true
while condition: # true
#do this
#do this
use case:
age = input()
while age < 18:
print(“invalid”)
age = input()
print(“good”)
for loop → execute a block of code a fixed number of times, you can iterate over anything that is
iterable
for i in range(1, 11): → runs 1 to 10
# do this
for i in range(10, 0, -1) → -1 step to go reversed
for i in var → where var is iterable
continue → keyword used to skip an iteration
4
break → break out of the loop entirely
import time → time module
time.sleep(num) → sleep for num seconds
nested loops → a loop within another loop
for i in range(var):
for j in range(var2):
# do this
# do this
# do this
print(var, end=“”) → end= ends your print statement with whatever you like instead of default
new line
Collections → single “var” used to store multiple values
list → [ ] ordered and changeable. dupes are okay
set → {} unordered and immutable, but add/remove are okay, no dupes
tuple → ( ) ordered and unchangled, dupes are okay, faster
dir(var) → list methods and attributes available with that type of collection
print(help(var)) as well or just documentation
len(var) → returns length of collection
“apple” in var → returns true if in collection
# list methods
list_name = [“apple”, “banana”, orange”]
list_name[2] → orange
for element in list_name:
# do this
lists can be changed using indices
list.append(var) → adds at the end of the list
list.remove(var) → removes from list
5
list.insert(index, value) → adds value at that index
list.sort() → sorts them in ascending order
list.reverse() → reverses the order of the list
list.clear() → clears the list
list.index(value) → returns index of value
list.count(value) → returns number of occurrences of value in lists
# set methods
can’t use index operating on sets because they are unordered
set.add(value) → adds value to set
set.remove(value) → removes value to set
set.pop() → pops first (random) value
set.clear() → clears the set
# tuple methods
tuple.index(value) → returns index of value in tuple
tuple.count(value) → num of occurrences of value in tuple
can iterate over all of them using for loop
2d lists → lists made up of lists
list_name = [list1, list2, list3]
list_name = [ [1,2,3],
[4,5,6],
[7,8,9] ]
how to access an individual element from 2d list → list_name[row][colum]
basically list_name[index of outerlist][index of element in that outlist]
iterable using a for loop as well ( nested loops if you want to access all of them or using a
counter + loop)
dictionary → a collection of {key:value} pairs, ordered and changeable. no dupes
dict_name = {key:value, key2:value2, key3:value3}
6
# dict methods
dict.get(key) → returns value associated with key or else None
dict.update({key:value}) → appends new or update existing pair
dict.pop(key) → removes key value pair
dict.popitem() → removes last pair
dict.clear() → clear the dict
dict.keys() → returns all keys in dict as an object, iterable
dict.values() → returns all values in dict as an object, iterable
dict.items() → returns all pairs in dict as an object, iterable
to iterate over items
for key, value in dict.items():
# do this
import random → import the random module
print(help(random)) → for help or check the documentation
random.randint(rangeStart, rangeEnd) → returns a random integer within range (inclusive)
random.random → return a random floating point number between 0 and 1
random.choice(collection) → returns a random element from the collection
random.shuffle(collection) → randomly shuffles collection
Functions → a block of reusable code, place () after the function name to invoke it
def function_name(): → how to define a function
# do this
function_name() → call/invoke the function
def function_name(parameter, par2): → optionally add parameter(s)
function_name(argument, arg2) → invoke with the argument/parameter(s)
return → statement used to end a function and send a result back to the caller
def func(): → use case of return
# do this
return value
value = func()
7
default arguments → a default value for certain parameters, default is used when that argument
in omitted, makes your function more flexible
def func(par1, par2 = value):
# do this
func(arg1) or func(arg1, arg2) → both work because par2 has a default value incase nothing is
passed in
you must ensure default arguments are after all the positional arguments
def fucn(par1 = value, par2): → this would result in a syntax error
keyword arguments → an argument preceded by an identifier, helps with readability, order of
args doesn't matter
def func(par1, par2, par3):
# do this
func(par1, par3 = value, par2 = value) → order does not matter if you use keyword arguments
you must ensure keyword arguments are after all the positional arguments
print(value, value, sep= “-”) → a lot of functions like print has keyword arguments too (end= /
sep=)
arbitrary arguments → varying amount of arguments
*args → allows you to pass multiple non-key arguments
**kwargs → allows you to pass multiple keyword-arguments
* → unpacking operator
def func(*args) → args is a tuple, iterable through a for loop (can name args to anything)
# do this
func(arg1, arg2, … argN)
def func(**kwargs) → kwargs is a dictionary, iteration through a for loop, keys separately or
values or both
# do this
func(arg1= value, arg2= value, … argN = value)
8
you can use both *args and **kwargs at the same time
def func(*args, **kwargs):
remember, positional arguments must always come first when invoking a function
Iterables → an object/collection that can return its element one at a time allowing it to be iterated
over in a loop
reversed → reverses a collection (expect sets)
membership operators → used to test whether a value or variable is found in a sequence, in and
not in
if var in sequence_var:
# do this
list comprehensions → a concise way to create lists in python, compact and easier to read
list = [i * 2 for i in range(1,11) ] → [expression/statement for value in iterable if condition] ←
formula (if condition is optional)
Match-case statement (switch) → an alternative to using many elif statements, cleaner
match variable:
case value:
# do this
case value:
# do this
case _: → uses an underscore, functions as an else statement
# do this
module → a file containing code you want to include in your program, use import
import module as variable_name
you can also assign multiple vars in one line → var1, var2 = value1, value2
you can import other files contents using import file_name to
9
variable scope → where a variable is visible and accessible
scope resolution → LEGB → order of operation → local, enclosed, global, built-in
variables declared within a function have a local scope
def func():
x=1
def func2():
x=2
a local value is given preference first, then enclosed if not found in local scope
global scope meaning outside of any function, accessible everywhere
built-in variables (e.g. euler’s constant or pi)
if __name__ == "__main__": → Only run this code if you are running this file directly, not if it’s
being imported
basically, it runs when you execute the file, doesn’t run when another file imports it, so your
functions/classes don’t auto execute
string.join(collection) → join each element and places string in between