🐍 python python cheat sheet

python

fukurou

the supreme coder
ADMIN
Python:
'''variables'''
age = 0    # implicit var declaration
isCompleted: bool = False # explicit var declaration
NUM: int = 2 # constant takes less space than var


'''strings'''
str1: str = "1+4=hello"
s1: str = f'Good {var1}! time to {var2}!'


'''classes'''
class MyClass(Object):
    myProperty: int

    def __init__(self) -> None:
        super().__init__()
        self.myProperty = 12

mClass: MyClass = MyClass() # object instance


'''methods'''
def myMethod() -> bool:
    return True

def methodWithParams(a: int, b: int) -> int:
    return a + b


'''varargs'''
def sum1(*values: int) -> int:
    total: int = 0
    for i in range(0, len(values)):
        total += values[i]
    return total

print(sum1(1, 4, 5))


'''arraylist'''
cars: list[str] = []  # Create an ArrayList object
cars.append("jag")
print(cars[0])


'''array'''
cars: list[str] = ["Volvo", "BMW", "Ford", "Mazda"]

arr_num = [0] * 2 # [0, 0]
arr_str = ['P'] * 5 # ['P', 'P', 'P', 'P', 'P']
arr = [0 for i in range(3)] # [0, 0, 0]


'''dictionary'''
dic1: dict[str, int] = {}
dic1["one"] = 1
dic1["two"] = 2
for x in dic1.keys():
    print(f"key :{x} value: {dic1[x]}")


'''if'''
time: int = 20
if (time < 18):
    print("Good day.")
else:
    print("Good evening.")

max = n1 if (n1 < n2) else n2 # return exp1 if true


'''loops'''
for i in range(1, 11):
# for each item loop :
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

while (condition):
  # code block to be executed

while True:
  # code block to be executed
    if (condition):
        break


'''switch'''
n:str = "test"
match n:
    case 'hello':
            print("hi there!")
    case 'y':
            print("y")
    case _:
            print("default case")


'''randomizer'''
import random
print(random.randint(0,9)) # 0 <= N <= 9
random.uniform(1.5, 1.9) # double random
round(random.uniform(1, 2), 2) # num in range with 2 decimal digits


'''N-dimensional arrays'''
matrix = [[0]*5 for i in range(5)] # 5 by five matrix with all values zero
print(matrix[1][1])
 
Last edited:
Top