1. variables ❎
A container for a value (string, integer, float, boolean)
A variable behaves as if it was the value it contains
# Strings
first_name = "Bro"
food = "pizza"
email = "Bro123@gmail.com"
print(f"Hello {first_name}")
print(f"You like {food}")
print(f"Your email is: {email}")
# Integers
age = 25
quantity = 3
num_of_students =30
print(f"You are {age} years old")
print(f"You are buying {quantity} items")
print(f"You class has {num_of_students} students")
# Float
price = 10.99
gpa = 3.2
distance = 5.5
print(f"The price is ${price}")
print(f"Your gpa is: {gpa}")
print(f"You ran {distance}km")
# Boolean
is_student = False
for_sale = False
is_online = True
if is_online:
print("You are online")
else:
print("You are offline")
Variable assignments
user_name = "Yuuniji"
year = 2025
pi = 3.14
is_admin = True
print(f"User Name: {user_name}")
print(f"Current Year: {year}")
# Round to two decimal places
print(f"Pi: {pi:.2f}")
# Convert boolean to 'Yes' or 'No'
print(f"Admin Status: {'Yes' if is_admin else 'No'}")
2. type casting 💱
Typecasting = the process of converting a variable from one data type to another
str(), int(), float(), bool()
name = "Yuuniji"
age = 25
gpa = 3.2
is_student = True
# print(type(name))
gpa = int(gpa) # 3
age = float(age) # 25.0
age = str(age)
age += "1" # "251"
name = bool(name) # True
3. user input ⌨️
A function that prompts the user to enter data
Returns the entered data as a string
name = input("What is your name?: ")
age = int(input("How old are you?: "))
# age = int(age)
age = age + 1
print(f"Hello {name}!")
print("HAPPY BIRTHDAY")
print(f"You are {age} years old")
Exercise 1 Rectangle Area Calc
length = float(intput("Enter the length: "))
width = float(intput("Enter the width: "))
area = length * width
print(f"The area is: {area}cm²")
#Mac superscript 2: Command + Control + Space, In the search bar, type “superscript” or “2”.Or Option + v
Exercise 2 Shopping Cart Program
item = input("What item would you like to buy?: ")
price = float(input("What is the price?: "))
quantity = int(input("How many would you like?: "))
total = price * quantity
print(f"You have bought {quantity} x {item}/s")
print(f"Your total is: ${total}")
4. ⭐ madlibs game
word game where you create a story
by filling in blanks with random words
adjective1 = input("Enter an adjective (description): ")
noun1 = input("Enter a noun (person, place, thing): ")
adjective2 = input("Enter an adjective (description): ")
verb1 = input("Enter a verb ending with 'ing'")
adjective3 = input("Enter an adjective (description): ")
print(f"Today I went to a {adjective1} zoo.")
print(f"In an exhibit, I saw a {noun1}")
print(f"{noun1} was {adjective2} and {verb1}")
print(f"I was {adjective3}!")
5. arithmetic operators & math functions 📐
friends = 10
friends = friends + 1
friends += 1
friends = friends - 2
friends -= 2
friends = friends * 3
friends *= 3
friends = friends / 2
friends /= 2
friends = friends ** 2
friends **= 2
remainder = friends % 3
x = 3.14
y = 4
z = 5
result = round(x) # 3
result = abs(y) # 4
result = pow(4, 3) # 4*4*4=64
result = max(x, y, z) # 5
result = min(x, y, z) # 3.14
import math
x = 9
y = 9.1
z = 9.9
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
result = math.sqrt(x) # 3.0
result = math.ceil(y) # 10
result = math.floor(z) # 9
# C = 2πr
import math
radius = float(input('Enter the radius of a circle: ')) # 10.5
circumference = 2 * math.pi *radius
print(f"The circumference is: {round(circumference, 2)}cm") # 65.97
# A = πr²
import math
radius = float(input('Enter the radius of a circle: ')) # 10.5
area = math.pi * pow(radius, 2)
print(f"The area of the circle is: {round(area, 2)}cm²") # 346.36
# c = √(a²+b²)
import math
a = float(input("Enter side A: ")) # 3
b = float(input("Enter side B: ")) # 4
c = math.sqrt(pow(a, 2) + pow(b, 2))
print(f"Side C = {c}") # 5.0
6. if statements 🤔
Do some code only IF some condition is True
Else do something else
age = int(input("Enter your age: "))
if age >= 100:
print("You are too old to sign up")
elif age >= 18:
print("You are now signed up!")
elif age < 0:
print("You haven't been born yet!")
else:
print("You must be 18+ to sign up")
resopnse = input("Would you like food? (Y/N): ")
if resopnse == "Y":
print("Have some food!")
else:
print("No food for you!")
name = inptut("Enter your name: ")
if name === "":
print("You did not type in your name!")
else:
print(f"Hello {name}")
for_sale = True
if for_sale:
print("This item is for sale")
else:
print("This item is NOT for sale")
7. ⭐ calculator program 🧮
# + = addition
# - = subtraction
# * = multiplication
# / = division
operator = input("Enter an operator (+ - * /)")
num1 = float(input("Enter the 1st number: "))
num2 = float(input("Enter the 2nd number: "))
if operator == "+":
result =num1 + num2
print(round(result, 3))
elif operator == "-":
result =num1 - num2
print(round(result, 3))
elif operator == "*":
result =num1 * num2
print(round(result, 3))
elif operator == "/":
result =num1 / num2
print(round(result, 3))
else:
print(f"{operator} is not a valid operator")
8. ⭐ weight conversion program 🏋️
weight = float(input("Enter your weight"))
unit = input("Kilograms or Pounds? (K or L): ")
if unit == "K":
weight = weight * 2.205
unit = "Lbs."
print(f"Your weight is: {round(weight, 1)} {unit}")
elif unit == "L":
weight = weight / 2.205
unit = "Kgs."
print(f"Your weight is: {round(weight, 1)} {unit}")
else:
print(f"{unit} was not valid")
9. ⭐ temperature conversion program 🌡️
# (°C x 9/5) + 32 = °F
# (°F - 32) x 5/9 = °C
# °(Option + Shift + 8)
unit = input("Is this temperature in Celsius or Fahrenheit (C/F): ")
temp = float(input("Enter the temperature: "))
if unit == "C":
temp = round((9 * temp) / 5 + 32, 1)
print(f"The temperature in Fahrenheit is: {temp}°F")
elif unit == "F":
temp = round((temp - 32) * 5 / 9, 1)
print(f"The temperature in Celsius is: {temp}°C")
else:
print(f"{unit} is an invalid unit of measurement")
10. logical operators 🌦️
evaluate multiple conditions (or, and, not)
or = at least one condition must be True
and = both conditions must be True
not = inverts the condition (not False, not True)
temp = 25
is_raining = True
if temp > 35 or temp < 0 or is_raining:
print("The outdoor event is cancelled")
else:
print("The outdoor event is still scheduled")
temp = 25
is_sunny = True
if temp >= 28 and is_sunny:
print("It is HOT outside 🥵")
print("It is SUNNY 🌞")
elif temp <= 0 and is_sunny:
print("It is COLD outside 🥶")
print("It is SUNNY 🌞")
elif 28 > temp > 0 and is_sunny:
print("It is WARM outside 🙂")
print("It is SUNNY 🌞")
elif temp >= 28 and not is_sunny:
print("It is HOT outside 🥵")
print("It is CLOUDY ☁️")
elif temp <= 0 and not is_sunny:
print("It is COLD outside 🥶")
print("It is CLOUDY ☁️")
elif 28 > temp > 0 and not is_sunny:
print("It is WARM outside 🙂")
print("It is CLOUDY ☁️")
11. conditional expressions ❓
A one-line shortcut for the if-else statement (ternary operator)
Print or assign one of two values based on a condition
X if condition else Y
num = 5
a = 6
b = 7
age = 13
temperature = 20
user_role = "guest"
print("Positive" if num > 0 else "Negative")
result = "EVEN" if num % 2 == 0 else "ODD"
max_num = a if a > b else b
min_num = a if a < b else b
status = "Adult" if age >= 18 else "Child"
weather = "HOT" if temperature > 20 else "COLD"
access_level = "Full Access" if user_role == "admin" else "Limited Access"
print(access_level)
12. string methods 〰️
name = input("Enter your full name: ")
result = len(name)
# yuunijiy -> 8
result = name.find("n")
# yuunijiy -> 3
result = name.rfind("n")
# yuunijiy -> 4
name = name.capitalize()
# yuunijiy -> Yuunijiy
name = name.upper()
# yuunijiy -> YUUNIJIY
name = name.lower()
# YUUNIJIY -> yuunijiy
result = name.isdigit()
# yuunijiy,yuu123 -> False; 123 -> True
result = name.isalpha()
# yuunijiy -> True; yuu niji,yuu123,123 -> False
phone_number = input("Enter your phone #: ")
result = phone_number.count("-")
# 1-234-567-8901 -> 3
phone_number = phone_number.replace("-", " ")
# 1-234-567-8901 -> 1 234 567 8901
If you want a complete list of all available string methods, use the help function:print(help(str))
Exercise:
# validate user input exercise
# 1. username is no more than 12 characters
# 2. username must not contain spaces
# 3. username must not contain digits
username = input("Enter a username: ")
if len(username) > 12:
print("Your username can't be more than 12 characters")
elif not username.find(" ") == -1:
print("Your username can't contain spaces")
elif not username.isalpha():
print("Your username can't contain digits")
else:
print(f"Welcome {username}")
13. string indexing ✂️
accessing elements of a sequence using [] (indexing operator)
[start : end : step]
credit_number = "1234-5678-9012-3456"
print(credit_number[0]) # 1
print(credit_number[:4]) # 1234
print(credit_number[5:9]) # 5678
print(credit_number[5:]) # 5678-9012-3456
print(credit_number[-1]) # 6
print(credit_number[-2]) # 5
print(credit_number[::2]) # 13-6891-46
print(credit_number[::3]) # 146-136
credit_number = "1234-5678-9012-3456"
last_digits = credit_number[-4:] # 3456
print(f"XXXX-XXXX-XXXX-{last_digits}")
credit_number = "1234-5678-9012-3456"
credit_number = credit_number[::-1]
print(credit_number)
# 6543-2109-8765-4321
14. format specifiers 💬
{value:flags} format a value based on what
flags are inserted
.(number)f
= round to that many decimal places (fixed point):(number)
= allocate that many spaces:03
= allocate and zero pad that many spaces:<
= left justify:>
= right justify:^
= center justify:+
= use a plus sign to indicate positive value:=
= place sign to leftmost position:
= insert a space before positive numbers:,
= comma separator
price1 = 3.14159
price2 = -987.65
price3 = 12.34
print(f"Price 1 is ${price1:.3f}") # 3.142
print(f"Price 2 is ${price2:.3f}") # -987.650
print(f"Price 3 is ${price3:.3f}") # 12.340
print(f"Price 1 is ${price1:10}")
print(f"Price 2 is ${price2:10}")
print(f"Price 3 is ${price3:10}")
# Price 1 is $ 3.14159
# Price 2 is $ -987.65
# Price 3 is $ 12.34
print(f"Price 1 is ${price1:010}")
print(f"Price 2 is ${price2:010}")
print(f"Price 3 is ${price3:010}")
# Price 1 is $0003.14159
# Price 2 is $-000987.65
# Price 3 is $0000012.34
print(f"Price 1 is ${price1:<10}")
print(f"Price 2 is ${price2:<10}")
print(f"Price 3 is ${price3:<10}")
# Price 1 is $3.14159 |
# Price 2 is $-987.65 |
# Price 3 is $12.34 |
print(f"Price 1 is ${price1:+}") # +3.14159
print(f"Price 2 is ${price2:+}") # -987.65
print(f"Price 3 is ${price3:+}") # +12.34
print(f"Price 1 is ${price1:10}")
print(f"Price 2 is ${price2:10}")
print(f"Price 3 is ${price3:10}")
# Price 1 is $ 3.14159
# Price 2 is $-987.65
# Price 3 is $ 12.34
price1 = 3000.14159
price2 = -9870.65
price3 = 1200.34
print(f"Price 1 is ${price1:,}")
print(f"Price 2 is ${price2:,}")
print(f"Price 3 is ${price3:,}")
# Price 1 is $3,000.14159
# Price 2 is $-9,870.65
# Price 3 is $1,200.34
print(f"Price 1 is ${price1:+,.2f}")
print(f"Price 2 is ${price2:+,.2f}")
print(f"Price 3 is ${price3:+,.2f}")
# Price 1 is $+3,000.14
# Price 2 is $-9,870.65
# Price 3 is $+1,200.34
15. while loops ♾️
execute some code WHILE some condition remains true
age = int(input("Enter your age: "))
while age < 0:
print("Age can't be negative")
age = int(input("Enter your age: "))
print(f"You are {age} years old")
food = input("Enter a food you like (q to quit): ")
while not food == "q":
print(f"You like {food}")
food = input("Enter another food you like (q to quit): ")
print("bye")
num = int(input("Enter a # between 1 - 10: "))
while num < 1 or num > 10:
print(f"{num} is not valid")
num = int(input("Enter a # between 1 - 10: "))
print(f"Your number is {num}")
16. ⭐ compound interest calculator 💵
# A = P (1 + r/n)ᵗ
# A = final amount
# P = initial principal balance
# r = interest rate
# t = number of time periods elapsed
principle = 0
rate = 0
time = 0
while principle <= 0:
principle = float(input("Enter the principle aount: "))
if principle <= 0:
print("Principle can't be less than or equal to zero")
while rate <= 0:
rate = float(input("Enter the interest rate: "))
if rate <= 0:
print("Interest rate can't be less than or equal to zero")
while time <= 0:
time = int(input("Enter the time in years: "))
if time <= 0:
print("Time can't be less than or equal to zero")
print(principle)
print(rate)
print(time)
total = principle * pow((1 + rate / 100), time)
print(f"Balance after {time} year/s: ${total:.2f}")
principle = 0
rate = 0
time = 0
while True:
principle = float(input("Enter the principle aount: "))
if principle < 0:
print("Principle can't be less than zero")
else:
break
while True:
rate = float(input("Enter the interest rate: "))
if rate < 0:
print("Interest rate can't be less than zero")
else:
break
while True:
time = int(input("Enter the time in years: "))
if time < 0:
print("Time can't be less than zero")
else:
break
total = principle * pow((1 + rate / 100), time)
print(f"Balance after {time} year/s: ${total:.2f}")
17. for loops 🔁
execute a block of code a fixed number of times.
You can iterate over a range, string, sequence, etc.
for x in range(1, 6):
print(x)
# 1
# 2
# 3
# 4
# 5
for x in reversed(range(1, 6)):
print(x)
print("HAPPY NEW YEAR!")
# 1
# 2
# 3
# 4
# 5
# HAPPY NEW YEAR!
for x in range(1, 6, 3):
print(x)
# 1
# 4
credit_card = "12-34"
for x in credit_card:
print(x)
# 1
# 2
# -
# 3
# 4
for x in range(1, 6):
if x == 3:
continue
else:
print(x)
# 1
# 2
# 4
# 5
for x in range(1, 6):
if x == 3:
break
else:
print(x)
# 1
# 2
18. ⭐ countdown timer program ⌛
import time
my_time = int(input("Enter the time in seconds: ")) # 3
for x in range(0, my_time):
print(x)
time.sleep(1)
# 0
# 1
# 2
print("TIME'S UP!")
import time
my_time = int(input("Enter the time in seconds: ")) # 3
for x in range(my_time, 0, -1):
print(x)
time.sleep(1)
# 3
# 2
# 1
print("TIME'S UP!")
import time
my_time = int(input("Enter the time in seconds: ")) # 3605
for x in range(my_time, 0, -1):
seconds = x % 60
minutes = int(x / 60) % 60
hours = int(x / 3600)
print(f"{hours:02}:{minutes:02}:{seconds:02}")
time.sleep(1)
# 01:00:05
# 01:00:04
# 01:00:03
# 01:00:02
# 01:00:01
# 01:00:00
# 00:59:59
# 00:59:58
print("TIME'S UP!")
19. nested loops ➿
A loop within another loop (outer, inner)
outer loop:
inner loop:
for x in range(1, 10):
print(x, end="")
# 123456789
for x in range(3):
for y in range(1, 10):
print(y, end="")
# 123456789123456789123456789
for x in range(3):
for y in range(1, 10):
print(y, end="")
print()
# 123456789
# 123456789
# 123456789
rows = int(input("Enter the # of rows: ")) # 3
columns = int(input("Enter the # of rows: ")) # 5
symbol = input("Enter a symbol to use: ") # *
for x in range(rows):
for y in range(columns):
print(symbol, end="")
print()
# *****
# *****
# *****
20. lists, sets, and tuples 🍎
- collection = single “variable” used to store multiple values
- List =
[]
ordered and changeable. Duplicates OK - Set =
{}
unordered and immutable, but Add/Remove OK. NO duplicates - Tuple =
()
ordered and unchangeable. Duplicates OK. FASTER
fruits = ["apple", "orange", "banana", "coconut"]
# print(help(fruits))
print(dir(fruits))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
print("apple" in fruits) # True
print(fruits[0]) # apple
print(fruits[0:3])
# ["apple", "orange", "banana"]
print(fruits[::2])
# ["apple", "banana"]
print(fruits[::-1])
# ["coconut", "banana", "orange", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.append("pineapple")
# fruits.remove("pineapple")
print(fruits)
# ["apple", "orange", "banana", "coconut", "pineapple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.insert(0, "pineapple")
print(fruits)
# ["pineapple", "apple", "orange", "banana", "coconut"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.sort()
print(fruits)
# ["apple", "banana", "coconut", "orange"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.reverse()
print(fruits)
# ["coconut", "banana", "orange", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.sort()
fruits.reverse()
print(fruits)
# ["orange", "coconut", "banana", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.clear()
print(fruits)
# []
fruits = ["apple", "orange", "banana", "coconut"]
print(fruits.index("apple")) # 0
fruits = {"apple", "orange", "banana", "coconut", "coconut"}
print(len(fruits)) # 4
print(dir(fruits))
# ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
print(fruits[0])
# TypeError: 'set' object is not subscriptable
print(fruits)
# {"orange", "apple", "banana", "coconut"}
fruits.pop()
# {"orange", "apple", "banana"}
# OR {"apple", "banana", "coconut"}
# OR {"orange", "banana", "coconut"}
# OR ...
fruits.clear() # set()
fruits = ("apple", "orange", "banana", "coconut", "coconut")
print(dir(fruits))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
print(fruits)
# ("apple", "orange", "banana", "coconut", "coconut")
21. ⭐ shopping cart program 🛒
foods = []
prices = []
total = 0
while True:
food = input("Enter a food to buy (q to quit): ")
if food.lower() == "q:
break
else:
price = float(input(f"Enter the price of a {food}: $"))
foods.append(food)
prices.append(price)
print("----- YOUR CART -----")
for food in foods:
print(food, end=" ")
for price in prices:
total += price
print()
print(f"Your total is: ${total}")
22. 2D collections ⬜
fruits = ["apple", "orange", "banana", "coconut"]
vegetables = ["celery", "carrots", "potatoes"]
meats = ["chicken", "fish", "turkey"]
groceries = [fruits, vegetables, meats]
print(groceries[0])
# ["apple", "orange", "banana", "coconut"]
print(groceries[0][3])
# coconut
print(groceries[2][3])
# IndexError: list index out of range
groceries = [["apple", "orange", "banana", "coconut"],
["celery", "carrots", "potatoes"],
["chicken", "fish", "turkey"]]
for collection in groceries:
for food in collection:
print(food, end=" ")
print()
# apple orange banana coconut
# celery carrots potatoes
# chicken fish turkey
num_pad = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#"))
for row in num_pad:
for num in row:
print(num, end=" ")
print()
# 1 2 3
# 4 5 6
# 7 8 9
# * 0 #
23. ⭐ quiz game 💯
question = ("How many elements are in the periodic table?: ",
"Which animal lays the largest eggs?: ",
"What is the most abundant gas in Earth's atmosphere?: ",
"How many bones are in the human body?: ",
"Which planet in the solar system is the hottest?: ")
options = (("A. 116", "B. 117", "C. 118", "D. 119"),
("A. Whale", "B. Crocodile", "C. Elephant", "D. Ostrich"),
("A. Nitrogen", "B. Oxygen", "C. Carbon-Dioxide", "D. Hydrogen"),
("A. 206", "B. 207", "C. 208", "D. 209"),
("A. Mercury", "B. Venus", "C. Earth", "D. Mars"))
answers = ("C", "D", "A", "A", "B" )
guesses = []
score = 0
question_num = 0
for question in questions:
print("-----------------------")
print(question)
for option in options[question_num]:
print(option)
guess = input("Enter (A, B, C, D): ").upper()
guesses.append(guess)
if guess == answers[question_num]:
score += 1
print("CORRECT!")
else:
print("INCORRECT!")
print(f"{answers[question_num]} is the correct answer")
question_num += 1
print("-----------------------")
print(" RESULTS ")
print("-----------------------")
print("answers: ", end="")
for answer in answers:
print(answer, end=" ")
print()
print("guesses: ", end="")
for guesse in guesses:
print(guesse, end=" ")
print()
score = int(score / len(questions) * 100)
print(f"Your score is: {score}%")
24. dictionaries 📙
a collection of {key:value} pairs ordered and changeable. No duplicates
capitals = {"USA": "Washington D.C.",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"}
print(dir(capitals))
# print(help(capitals))
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(capitals.get("USA")) # Washington D.C.
print(capitals.get("Japan")) # None
capitals.update({"Germany": "Berlin"})
capitals.update({"USA": "Detroit"})
# {"USA": "Detroit", "India": "New Delhi", "China": "Beijing", "Russia": "Moscow", "Germany": "Berlin"}
capitals.pop("China")
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow", "Germany": "Berlin"}
capitals.popitem()
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow"}
# capitals.clear()
# {}
keys = capitals.keys()
# dict_keys(['USA', 'India', 'Russia'])
for keys in capitals.keys():
print(key)
# USA
# India
# Russia
values = capitals.values()
# dict_values(['Detroit', 'New Delhi', 'Moscow'])
for value in capitals.values():
print(value)
# Detroit
# New Delhi
# Moscow
items = capitals.items()
print(items)
# dict_items([('USA', 'Detroit'), ('India', 'New Delhi'), ('Russia', 'Moscow')])
for key, value in capitals.items():
print(f"{key}: {value}")
# USA: Detroit
# India: New Delhi
# Russia: Moscow
25. ⭐ concession stand program 🍿
menu = {"pizza": 3.00,
"nachos": 4.50,
"popcorn": 6.00,
"fries": 2.50,
"chips": 1.00,
"pretzel": 3.50,
"soda": 3.00,
"lemonade": 4.25}
cart = []
total = 0
print("----- MENU -----")
for key, value in menu.items():
print(f"{key:10}: ${value:.2f}")
print("----------------")
while True:
food = input("Select an item (q to quit): ").lower()
if food == "q":
break
elif menu.get(food) is not None:
cart.append(food)
print("-- YOUR ORDER --")
for food in cart:
total += menu.get(food)
print(food, end=" ")
print()
print(f"Total is: ${total:.2f}")
26. random numbers 🎲
import random
# print(help random)
low = 1
high = 100
options = ("rock", "paper", "scissors")
cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
# number = random.randint(1, 6)
# number = random.randint(low, high)
# number = random.random()
# option = random.choice(options)
# random.shuffle(cards)
27. ⭐ number guessing game 🔢
import random
lowest_num = 1
highest_num = 100
answer = random.randint(lowest_num, highest_num)
guesses = 0
is_running = True
print("Python Number Guessing Game")
print(f"Select a number between {lowest_num} and {highest_num}")
while is_running:
guess = input("Enter your guess: ")
if guess.isdigit():
guess = int(guess)
guesses += 1
if guess < lowest_num or guess > highest_num:
print("That number is out of range")
print(f"Please select a number between {lowest_num} and {highest_num}")
elif guess < answer:
print("Too low! Try again!")
elif guess > answer:
print("Too high! Try again!")
else:
print(f"CORRECT! The answer was {answer}")
print(f"Number of guesses: {guesses}")
is_running = False
else:
print("Invalid guess")
print(f"Please select a number between {lowest_num} and {highest_num}")
28. ⭐ rock, paper, scissors game 🗿
import random
options = ("rock", "paper", "scissors")
playing = True
while playing:
player = None
computer = random.choice(options)
while player not in options:
player = input("Enter a choice (rock, paper, scissors):")
print(f"Player: {player}")
print(f"Computer: {computer}")
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "paper" and computer == "rock":
print("You win!")
elif player == "scissors" and computer == "paper":
print("You win!")
else:
print("You lose!")
play_again = input("Play again? (y/n): ").lower()
if not play_again == "y":
playing = False
print("Thanks for playing!")
29. ⭐ dice roller program ⚂
import random
print("\u25CF \u250C \u2500 \u2510 \u2502 \u2514 \u2518")
# ● ┌ ─ ┐ │ └ ┘
"┌─────────┐"
"│ │"
"│ │"
"│ │"
"└─────────┘"
dice_art = {
1: ("┌─────────┐",
"│ │",
"│ ● │",
"│ │",
"└─────────┘"),
2: ("┌─────────┐",
"│ ● │",
"│ │",
"│ ● │",
"└─────────┘"),
3: ("┌─────────┐",
"│ ● │",
"│ ● │",
"│ ● │",
"└─────────┘"),
4: ("┌─────────┐",
"│ ● ● │",
"│ │",
"│ ● ● │",
"└─────────┘"),
5: ("┌─────────┐",
"│ ● ● │",
"│ ● │",
"│ ● ● │",
"└─────────┘"),
6: ("┌─────────┐",
"│ ● ● │",
"│ ● ● │",
"│ ● ● │",
"└─────────┘"),
}
dice = []
total = 0
num_of_dice = int(input("How many dice?: "))
for die in range(num_of_dice):
dice.append(random.randint(1, 6))
print(dice)
# for die in range(num_of_dice):
# for line in dice_art.get(dice[die]):
# print(line)
for line in range(5): # 外部循环,按行打印
for die in dice: # 内部循环,遍历每个骰子的点数
print(dice_art.get(die)[line], end="") # 打印当前骰子图案的当前行
print() # 每打印完一行后换行
for die in dice:
total += die
print(f"total: {total}")
30. functions 📞
# function = A block of reusable code
# place () after the function name to invoke it
def happy_birthday(name, age):
print(f"Happy birthday to {name}!")
print("You are {age}!")
print("Happy birthday to you!")
print()
happy_birthday("Bro", 20)
happy_birthday("Steve", 30)
happy_birthday("Joe", 40)
--------
def display_invoice(username, amount, due_date):
print(f"Hello {username}")
print(f"Your bill of ${amount:.2f} is due: {due_date}")
display_invoice("YuuNiji", 100.01, "01/02")
--------
# return = statement used to end a function
# and send a result back to the caller
def add(x, y):
z = x + y
return z
def subtract(x, y):
z = x - y
return z
def multiply(x, y):
z = x * y
return z
def divide(x, y):
z = x / y
return z
print(add(1, 2)) # 3
print(subtract(1, 2)) # -1
print(multiply(1, 2)) # 2
print(divide(1, 2)) # 0.5
--------
def create_name(first, last):
first = first.capitalize()
last = last.capitalize()
return first + " " + last
full_name = create_name("yuuniji", "code")
print(full_name) # Yuuniji Code
31. default arguments 👍
# default arguments = A default value for certain parameters
# default is used when that argument is omitted
# make your functions more flexible, reduces # of arguments
# 1. positional, 2. DEFAULT, 3. keyword, 4. arbitrary
def net_price(list_price, discount=1, tax=0.05):
return list_price * (1 - discount) * (1 + tax)
print(net_price(500)) # 525.0
print(net_price(500, 0.1)) # 472.5
print(net_price(500, 0.1, 0)) # 450
--------
import time
def count(start, end):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("DONE!")
count(0, 10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# DONE!
--------
import time
def count(start=0, end):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("DONE!")
count(10)
# SyntaxError: non-default argument follows default argument
--------
import time
def count(end, start=0):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("DONE!")
count(10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# DONE!
--------
import time
def count(end, start=0):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("DONE!")
count(30, 15)
# 15
# 16
# 17
# 18
# 19
# 20
# 21
# 22
# 23
# 24
# 25
# 26
# 27
# 28
# 29
# 30
# DONE!
32. keyword arguments 🗝️
# keyword arguments = an argument preceded by an identifier
# helps with readability
# order of arguments doesn't matter
# 1. positional 2. default 3. KEYWORD 4. arbitrary
def hello(greeting, title, first, last):
print(f"{greeting} {title}{first} {last}")
hello("Hello", "Mr.", "Spongebob", "Squarepants")
# Hello Mr.Spongebob Squarepants
hello("Hello", "Spongebob", "Squarepants", "Mr.")
# Hello SpongebobSquarepants Mr.
hello("Hello", title="Mr.", first="Spongebob", last="Squarepants")
# Hello Mr.Spongebob Squarepants
hello("Hello", title="Mr.", last="Squarepants", first="Spongebob")
# Hello Mr.Spongebob Squarepants
hello(title="Mr.", last="Squarepants", first="Spongebob", "Hello")
# SyntaxError: positional argument follows keyword argument
hello("Hello", "Mr.", "John", "James")
# Hello Mr.John James
hello("Hello", title="Mr.", last="John", first="James")
# Hello Mr.James John
--------
for x in range(1, 11):
print(x, end=" ")
# 1 2 3 4 5 6 7 8 9 10
--------
print("1", "2", "3", "4", "5", sep="-")
# 1-2-3-4-5
--------
def get_phone(country, area, first, last):
return f"{country}-{area}-{first}-{last}"
phone_num = get_phone(country=1, area=123, first=456, last=7890)
print(phone_num)
# 1-123-456-7890
33. *args & **kwargs 📦
# *args = allows you to pass multiple non-key arguments
# **kwargs = allows you to pass multiple keyword-arguments
# * unpacking operator
# 1. positional 2. default 3. keyword 4. ARBITRARY
def add(a, b):
return a + b
print(add(1, 2)) # 3
print(add(1, 2, 3))
# TypeError: add() takes 2 positional arguments but 3 were given
--------
def add(*args):
print(type(args)) # <class 'tuple'>
total = 0
for arg in args:
total += arg
return total
print(add(1, 2, 3, 4, 5)) # 15
--------
def display_name(*args):
for arg in args:
print(arg, end=" ")
display_name("Dr.", "Spongebob", "Harold", "Squarepants")
# Dr. Spongebob Harold Squarepants
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for value in kwargs.values():
print(value)
print_address(street="123 Fake St.",
city="Detroit",
state="MI",
zip="54321")
# 123 Fake St.
# Detroit
# MI
# 54321
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for key in kwargs.keys():
print(key)
print_address(street="123 Fake St.",
city="Detroit",
state="MI",
zip="54321")
# street
# city
# state
# zip
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for key, value in kwargs.items():
print(f"{key}: {value}")
print_address(street="123 Fake St.",
city="Detroit",
state="MI",
zip="54321")
# street: 123 Fake St.
# city: Detroit
# state: MI
# zip: 54321
--------
# def shipping_label(**kwargs, *args):
# SyntaxError: invalid syntax
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
shipping_label("Dr.", "Spongebob", "Squarepants", "III",
street="123 Fake St.",
apt="100",
city="Detroit",
state="MI",
zip="54321")
# Dr. Spongebob Squarepants III
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
for value in kwargs.values():
print(value, end=" ")
shipping_label("Dr.", "Spongebob", "Squarepants", "III",
street="123 Fake St.",
apt="100",
city="Detroit",
state="MI",
zip="54321")
# Dr. Spongebob Squarepants III
# 123 Fake St. 100 Detroit MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("Dr.", "Spongebob", "Squarepants",
street="123 Fake St.",
apt="#100",
city="Detroit",
state="MI",
zip="54321")
# Dr. Spongebob Squarepants
# 123 Fake St. #100
# Detroit MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("Dr.", "Spongebob", "Squarepants",
street="123 Fake St.",
city="Detroit",
state="MI",
zip="54321")
# Dr. Spongebob Squarepants
# 123 Fake St. None
# Detroit MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
if "apt" in kwargs:
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
elif "pobox" in kwargs:
print(f"{kwargs.get('street')}")
print(f"{kwargs.get('pobox')}")
else:
print(f"{kwargs.get('street')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("Dr.", "Spongebob", "Squarepants",
street="123 Fake St.",
pobox="PO box #1001",
city="Detroit",
state="MI",
zip="54321")
# Dr. Spongebob Squarepants
# 123 Fake St.
# PO box #1001
# Detroit MI 54321
34. iterables 🔂
# Iterables = An object/collection that can return its elements one at a time,
# allowing it to be iterated over in a loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# 1
# 2
# 3
# 4
# 5
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number)
# 5
# 4
# 3
# 2
# 1
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=" ")
# 5 4 3 2 1
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end="-")
# 5-4-3-2-1-
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=" - ")
# 5 - 4 - 3 - 2 - 1 -
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)
# 1
# 2
# 3
# 4
# 5
fruits = {"apple", "orange", "banana", "coconut"}
for fruit in fruits:
print(fruit)
# apple
# orange
# banana
# coconut
fruits = {"apple", "orange", "banana", "coconut"}
for fruit in reversed(fruits):
print(fruit)
# TypeError: 'set' object is not reversible
name ="Yuu Niji"
for character in name:
print(character)
# Y
# u
# u
# N
# i
# j
# i
name ="Yuu Niji"
for character in name:
print(character, end=" ")
# Y u u N i j i
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key in my_dictionary:
print(key)
# A
# B
# C
my_dictionary = {"A": 1, "B": 2, "C": 3}
for value in my_dictionary.value():
print(value)
# 1
# 2
# 3
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key, value in my_dictionary.items():
print(key, value)
# A 1
# B 2
# C 3
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key, value in my_dictionary.items():
print(f"{key} = {value}")
# A = 1
# B = 2
# C = 3
35. membership operators 🔎
# Membership operators = used to test whether a value or variable is found in a sequence
# (string, list, tuple, set, or dictionary)
# 1. in
# 1. not in
word = "APPLE"
letter = input("Guess a letter in the secret word: ")
if letter in word:
print(f"There is a {letter}")
else:
print(f"{letter} was not found")
# Guess a letter in the secret word: A
# There is a A
# Guess a letter in the secret word: Z
# Z was not found
word = "APPLE"
letter = input("Guess a letter in the secret word: ")
if letter not in word:
print(f"{letter} was not found")
else:
print(f"There is a {letter}")
# Guess a letter in the secret word: E
# There is a E
# Guess a letter in the secret word: Q
# Q was not found
students = {"Spongbob", "Patrick", "Sandy"}
student = input("Enter the name of a student: ")
if student in students:
print(f"{student} is a student")
else:
print(f"{student} was not found")
# Enter the name of a student: Spongbob
# Spongbob is a student
# Enter the name of a student: Yuuniji
# Yuuniji was not found
students = {"Spongbob", "Patrick", "Sandy"}
student = input("Enter the name of a student: ")
if student not in students:
print(f"{student} was not found")
else:
print(f"{student} is a student")
# Enter the name of a student: Sandy
# Sandy is a student
# Enter the name of a student: Github
# Github was not found
grades = {"Sandy": "A",
"Squidward": "B",
"Spongbob": "C",
"Patrick": "D"}
student = input("Enter the name of a student: ")
if student in grades:
print(f"{student}'s grade is {grades[student]}")
else:
print(f"{student} was not found")
# Enter the name of a student: Spongbob
# Spongbobs grade is C
# Enter the name of a student: Sandy
# Sandy grade is A
# Enter the name of a student: Squidward
# Squidward grade is B
# Enter the name of a student: Patrick
# Patrick grade is D
# Enter the name of a student: Yuuniji
# Yuuniji was not found
email = "yuuniji81@gmail.com"
if "@" in email and "." in email:
print("Valid email")
else:
print("Invalid email")
# Valid email
email = "yuuniji81gmail.com"
if "@" in email and "." in email:
print("Valid email")
else:
print("Invalid email")
# Invalid email
email = "yuuniji81@gmailcom"
if "@" in email and "." in email:
print("Valid email")
else:
print("Invalid email")
# Invalid email
36. list comprehensions 📃
# List comprehension = A concise way to create lists in Python
# Compact and easier to read than traditional loops
# [expression for value in iterable if condition]
doubles = []
for x in range(1, 11):
doubles.append(x * 2)
print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
doubles = [x * 2 for x in range(1, 11)]
print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
triples = [y * 3 for y in range(1, 11)]
print(triples)
# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
squares = [z * z for z in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
fruits = ["apple", "orange", "banana", "coconut"]
fruits = [fruit.upper() for fruit in fruits]
print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = [fruit.upper() for fruit in ["apple", "orange", "banana", "coconut"]]
print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = ["apple", "orange", "banana", "coconut"]
fruit_chars = [fruit[0] for fruit in fruits]
print(fruit_chars)
# ['a', 'o', 'b', 'c']
numbers = [1, -2, 3, -4, 5, -6, 8, -7]
positive_nums = [num for num in numbers if num >= 0]
negative_nums = [num for num in numbers if num < 0]
even_nums = [num for num in numbers if num % 2 == 0]
odd_nums = [num for num in numbers if num % 2 == 1]
print(positive_nums)
# [1, 3, 5, 8]
print(negative_nums)
# [-2, -4, -6, -7]
print(even_nums)
# [-2, -4, -6, 8]
print(odd_nums)
# [1, 3, 5, -7]
grades = [85, 42, 79, 90, 56, 61, 30]
passing_grades = [grade for grade in grades if grade >= 60]
print(passing_grades)
# [85, 79, 90, 61]
37. match-case statements 📆
# Match-case statement (switch): An alternative to using many 'elif' statements
# Execute some code if a value matches a 'case'
# Benefits: cleaner and syntax is more readable
def day_of_week(day):
if day == 1:
return "It is Sunday"
elif day == 2:
return "It is Monday"
elif day == 3:
return "It is Tuesday"
elif day == 4:
return "It is Wednesday"
elif day == 5:
return "It is Thursday"
elif day == 6:
return "It is Friday"
elif day == 7:
return "It is Saturday"
else:
return "Not a valid day"
print(day_of_week(1))
# It is Sunday
def day_of_week(day):
match day:
case 1:
return "It is Sunday"
case 2:
return "It is Monday"
case 3:
return "It is Tuesday"
case 4:
return "It is Wednesday"
case 5:
return "It is Thursday"
case 6:
return "It is Friday"
case 7:
return "It is Saturday"
case _: # _ = wild card
return "Not a valid day"
print(day_of_week(1))
# It is Sunday
def is_weekend(day):
match day:
case "Sunday":
return True
case "Monday":
return False
case "Tuesday":
return False
case "Wednesday":
return False
case "Thursday":
return False
case "Friday":
return False
case "Saturday":
return True
case _: # _ = wild card
return False
print(is_weekend("Sunday"))
# True
def is_weekend(day):
match day:
case "Saturday" | "Sunday": # | = or
return True
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return False
case _: # _ = wild card
return False
print(is_weekend("Sunday"))
# True
38. modules 📨
# Module = a file containing code you want to include in your program
# use 'import' to include a module (built-in or your own)
# useful to break up a large program reusable separate files
# print(help("modules"))
# print(help("math"))
import math
print(math.pi)
# 3.141592653589794
import math as m
print(math.pi)
# NameError: name 'math' is not defined
import math as m
print(m.pi)
# 3.141592653589794
from math import pi
print(pi)
# 3.141592653589794
from math import e
print(e)
# 2.718281828459045
from math import e
a, b, c, d = 1, 2, 3, 4
print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
from math import e
a, b, c, d, e = 1, 2, 3, 4, 5
print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
print(e ** e)
# 5
# 25
# 125
# 625
# 3125
import math
a, b, c, d, e = 1, 2, 3, 4, 5
print(math.e ** a)
print(math.e ** b)
print(math.e ** c)
print(math.e ** d)
print(math.e ** e)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
# 148.41315910257657
# example.py
pi = 3.14159
def square(x):
return x ** 2
def cube(x):
return x ** 3
def circumference(radius):
return 2 * pi * radius
def area(radius):
return pi * radius ** 2
# main.py
import example
result = example.pi
print(result)
# 3.14159
import example
result = example.square(3)
print(result)
# 9
import example
result = example.cube(3)
print(result)
# 27
import example
result = example.circumference(3)
print(result)
# 18.849539999999998
import example
result = example.area(3)
print(result)
# 28.27431
39. scope resolution 🔬
# variable scope = where a variable is visible and accessible
# scope resolution = (LEGB) Local -> Enclosed -> Global -> Built-in
def func1():
a = 1
print(a)
def func2():
b = 2
print(b)
func1() # 1
func2() # 2
def func1():
a = 1
print(b)
def func2():
b = 2
print(a)
func1()
func2()
# NameError: name 'b' is not defined
def happy_birthday(name, age):
print(f"Happy birthday dear {name}")
print(f"You are {age} years old")
def main():
name = "Yuuniji"
age = 21
happy_birthday(name, age)
main()
def func1():
x = 1
print(x)
def func2():
x = 2
print(x)
func1() # 1
func2() # 2
def func1():
x = 1
def func2():
x = 2
print(x)
func2()
func1()
# 2
def func1():
x = 1
def func2():
print(x)
func2()
func1()
# 1
def func1():
print(x)
def func2():
print(x)
x = 3
func1() # 3
func2() # 3
def func1():
x = 1
print(x)
def func2():
x = 2
print(x)
x = 3
func1() # 1
func2() # 2
from math import e
print(e)
# 2.718281828459045
from math import e
def func1():
print(e)
func1()
# 2.718281828459045
from math import e
def func1():
print(e)
e = 3
func1()
# 3
40. if name == ‘main’: 📥
# if __name__ == __main__: (this script can be imported OR run standalone)
# Functions and classes in this module can be reused without the main block of code executing
# Good practice (code is modular,
# helps readability,
# leaves no global variables,
# avoid unintended execution)
# Ex. library = Import library for functionality
# When running library directly, display a help page
def main():
# Your program goes here
if __name__ == '__main__':
main()
# script1.py
# print(dir())
print(__name__)
# __main__
# script1.py
from script2 import *
# When script2.py is imported by script1.py, it is treated as a module, not the main script. Therefore, Python sets its __name__ to the name of the module, which is "script2" (the name of the file without the .py extension).
# The print(__name__) statement in script2.py executes during the import process, printing "script2".
print(__name__)
# script2
# __main__
--------
# script2.py
print(__name__)
# script1.py
print(__name__)
# script2
# __main__
--------
# script2.py
from script1 import *
print(__name__)
# script1
# __main__
# script1.py
def favorite_food(food):
print(f"Your favorite food is {food}")
def main():
print("This is script1")
favorite_food("pizza")
print("Goodbye!")
if __name__ == '__main__':
main()
# This is script1
# Your favorite food is pizza
# Goodbye!
--------
# script2.py
from script1 import *
#
# script1.py
def favorite_food(food):
print(f"Your favorite food is {food}")
print("This is script1")
favorite_food("pizza")
print("Goodbye!")
--------
# script2.py
from script1 import *
# This is script1
# Your favorite food is pizza
# Goodbye!
# script1.py
def favorite_food(food):
print(f"Your favorite food is {food}")
def main():
print("This is script1")
favorite_food("pizza")
print("Goodbye!")
if __name__ == '__main__':
main()
--------
# script2.py
from script1 import *
def favorite_drink(drink):
print(f"Your favorite drink is {drink}")
print("This is script2")
favorite_food("sushi")
favorite_drink("coffee")
print("Goodbye!")
# This is script2
# Your favorite food is sushi
# Your favorite drink is coffee
# Goodbye!
# script1.py
def favorite_food(food):
print(f"Your favorite food is {food}")
def main():
print("This is script1")
favorite_food("pizza")
print("Goodbye!")
if __name__ == '__main__':
main()
--------
# script2.py
from script1 import *
def favorite_drink(drink):
print(f"Your favorite drink is {drink}")
def main():
print("This is script2")
favorite_food("sushi")
favorite_drink("coffee")
print("Goodbye!")
if __name__ == '__main__':
main()
# This is script2
# Your favorite food is sushi
# Your favorite drink is coffee
# Goodbye!
41. ⭐ banking program 💰
# Python Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
def show_balance():
pass
def deposit():
pass
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("Banking Program")
print("1. Show Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("That is not valid choice")
print("Thank you! Have a nice day!")
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 4
# Thank you! Have a nice day!
def show_balance():
print(f"Your balance is ${balance:.2f}")
def deposit():
amount = float(input("Enter an amount to be deposited: "))
if amount < 0:
print("That's not a valid amount")
else:
return amount
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("Banking Program")
print("1. Show Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
balance += deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("That is not valid choice")
print("Thank you! Have a nice day!")
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $0.00
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 2
# Enter an amount to be deposited: 100
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $100.00
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 2
# Enter an amount to be deposited: -420.69
# That's not a valid amount
# TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'
def show_balance():
print(f"Your balance is ${balance:.2f}")
def deposit():
amount = float(input("Enter an amount to be deposited: "))
if amount < 0:
print("That's not a valid amount")
return 0
else:
return amount
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("Banking Program")
print("1. Show Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
balance += deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("That is not valid choice")
print("Thank you! Have a nice day!")
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 2
# Enter an amount to be deposited: -420.69
# That's not a valid amount
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 2
# Enter an amount to be deposited: 50.01
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $50.01
def show_balance():
print(f"Your balance is ${balance:.2f}")
def deposit():
amount = float(input("Enter an amount to be deposited: "))
if amount < 0:
print("That's not a valid amount")
return 0
else:
return amount
def withdraw():
amount = input("Enter amount to be withdrawn: ")
if amount > balance:
print("Insufficient funds")
return 0
elif amount < 0:
print("Amount must be greater than 0")
return 0
else:
return amount
balance = 0
is_running = True
while is_running:
print("Banking Program")
print("1. Show Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
balance += deposit()
elif choice == '3':
balance -= withdraw()
elif choice == '4':
is_running = False
else:
print("That is not valid choice")
print("Thank you! Have a nice day!")
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $0.00
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 2
# Enter an amount to be deposited: 100
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $100.00
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 3
# Enter amount to be withdrawn: 1000000000000000000000
# Insufficient funds
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 3
# Enter amount to be withdrawn: -420.69
# Amount must be greater than 0
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 3
# Enter amount to be withdrawn: -49.99
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 1
# Your balance is $50.01
# Banking Program
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# Enter your choice (1-4): 4
# Thank you! Have a nice day!
def show_balance(balance):
print("*********************")
print(f"Your balance is ${balance:.2f}")
print("*********************")
def deposit():
print("*********************")
amount = float(input("Enter an amount to be deposited: "))
print("*********************")
if amount < 0:
print("*********************")
print("That's not a valid amount")
print("*********************")
return 0
else:
return amount
def withdraw(balance):
print("*********************")
amount = input("Enter amount to be withdrawn: ")
print("*********************")
if amount > balance:
print("*********************")
print("Insufficient funds")
print("*********************")
return 0
elif amount < 0:
print("*********************")
print("Amount must be greater than 0")
print("*********************")
return 0
else:
return amount
def main():
balance = 0
is_running = True
while is_running:
print("*********************")
print(" Banking Program ")
print("*********************")
print("1. Show Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
print("*********************")
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_balance(balance)
elif choice == '2':
balance += deposit()
elif choice == '3':
balance -= withdraw(balance)
elif choice == '4':
is_running = False
else:
print("*********************")
print("That is not valid choice")
print("*********************")
print("*********************")
print("Thank you! Have a nice day!")
print("*********************")
if __name__ == '__main__':
main()
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 1
# *********************
# Your balance is $0.00
# *********************
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 2
# *********************
# Enter an amount to be deposited: 100.01
# *********************
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 1
# *********************
# Your balance is $100.01
# *********************
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 3
# Enter amount to be withdrawn: 1000
# *********************
# Insufficient funds
# *********************
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 3
# Enter amount to be withdrawn: 50
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 1
# *********************
# Your balance is $50.01
# *********************
# *********************
# Banking Program
# *********************
# 1. Show Balance
# 2. Deposit
# 3. Withdraw
# 4. Exit
# *********************
# Enter your choice (1-4): 4
# *********************
# Thank you! Have a nice day!
# *********************
42. ⭐ slot machine 🎰
# Python Slot Machine
def spin_row():
pass
def print_row():
pass
def get_payout():
pass
def main():
pass
if __name__ == '__main__':
main()
def spin_row():
pass
def print_row():
pass
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: pizza
# Please enter a valid number
# Current balance: $100
# Place your bet amount: 10000000000000000
# Insufficient funds
# Current balance: $100
# Place your bet amount: 0
# Bet must be greater than 0
# Current balance: $100
# Place your bet amount: 1
# Current balance: $99
# Place your bet amount: 10
# Current balance: $89
# Place your bet amount: 90
# Insufficient funds
# Current balance: $89
# Place your bet amount: 89
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row():
pass
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
row = spin_row()
print(row)
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: 1
# ['⭐️', '🍋', '🍋']
# Current balance: $99
# Place your bet amount: 1
# ['🍉', '🍒', '⭐️']
# Current balance: $98
# Place your bet amount: 1
# ['🍒', '🍉', '🍒']
# Current balance: $97
# Place your bet amount: 1
# ['⭐️', '🍋', '⭐️']
# Current balance: $96
# Place your bet amount: 1
# ['🍋', '🍒', '🍋']
# Current balance: $95
# Place your bet amount:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print(" ".join(row))
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
row = spin_row()
print("Spinning...\n")
print_row(row)
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: 1
# Spinning...
#
# 🍋 ⭐️ 🔔
# Current balance: $99
# Place your bet amount:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
row = spin_row()
print("Spinning...\n")
print_row(row)
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: 1
# Spinning...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# Current balance: $99
# Place your bet amount: 2
# Spinning...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# Current balance: $97
# Place your bet amount: 3
# Spinning...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# Current balance: $94
# Place your bet amount: 4
# Spinning...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# Current balance: $90
# Place your bet amount:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout(row, bet):
if row[0] == row[1] == row[2]:
if row[0] == '🍒':
return bet * 3
elif row[0] == '🍉':
return bet * 4
elif row[0] == '🍋':
return bet * 5
elif row[0] == '🔔':
return bet * 10
elif row[0] == '⭐️':
return bet * 20
return 0
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
row = spin_row()
print("Spinning...\n")
print_row(row)
payout = get_payout(row, bet)
if payout > 0:
print(f"You won ${payout}")
else:
print("Sorry you lost this round")
balance += payout
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: 1
# Spinning...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# Sorry you lost this round
# Current balance: $99
# Place your bet amount: 2
# Spinning...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# Sorry you lost this round
# Current balance: $97
# Place your bet amount: 3
# Spinning...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# Sorry you lost this round
# Current balance: $94
# Place your bet amount: 1
# Spinning...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# You won $4
# Current balance: $93
# Place your bet amount:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout(row, bet):
if row[0] == row[1] == row[2]:
if row[0] == '🍒':
return bet * 3
elif row[0] == '🍉':
return bet * 4
elif row[0] == '🍋':
return bet * 5
elif row[0] == '🔔':
return bet * 10
elif row[0] == '⭐️':
return bet * 20
return 0
def main():
balance = 100
print("*************************")
print("Welcome to Python Slots ")
print("Symbols: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"Current balance: ${balance}")
bet = input("Place your bet amount: ")
if not bet.isdigit():
print("Please enter a valid number")
continue
bet = int(bet)
if bet > balance:
print("Insufficient funds")
continue
if bet < 0:
print("Bet must be greater than 0")
continue
balance -= bet
row = spin_row()
print("Spinning...\n")
print_row(row)
payout = get_payout(row, bet)
if payout > 0:
print(f"You won ${payout}")
else:
print("Sorry you lost this round")
balance += payout
play_again = input("Do you want to spin again? (Y/N): ").upper()
if play_again != 'Y':
break
print("*******************************************")
print(f"Game over! Your final balance is ${balance}")
print("*******************************************")
if __name__ == '__main__':
main()
# *************************
# Welcome to Python Slots
# Symbols: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# Current balance: $100
# Place your bet amount: 1
# Spinning...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# Sorry you lost this round
# Do you want to spin again? (Y/N): y
# Current balance: $99
# Place your bet amount: 5
# Spinning...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# Sorry you lost this round
# Do you want to spin again? (Y/N): y
# Current balance: $94
# Place your bet amount: 90
# Spinning...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# Sorry you lost this round
# Do you want to spin again? (Y/N): y
# Current balance: $4
# Place your bet amount: 1
# Spinning...
#
# *************
# 🔔 | 🔔 | 🔔
# *************
# You won $10
# Do you want to spin again? (Y/N): n
# ******************************************
# Game over! Your final balance is $14
# ******************************************
43. ⭐ encryption program 🔐
import string
# chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars = " " + string.punctuation + string.digits + string.ascii_letters
print(chars)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
print(chars)
# [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
print(f"chars: {chars}")
print(f"key : {key}")
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
print(f"chars: {chars}")
print(f"key : {key}")
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', ' ', 'N', '^', ']', 'u', 'H', '/', 'l', 'z', 'v', 'c', ';', 'p', '_', 'M', '#', 'r', '3', 'J', 'e', 'D', 'I', '&', '2', '1', 'W', 't', 'j', '@', 'h', '6', 'i', '0', 'y', '.', 'Z', 'U', 'P', 'A', 'd', 'n', 'T', '4', 'E', 'x', 'Q', '7', 'f', '-', '"', 'o', 'b', '8', '|', '$', '~', 'C', 'X', 'R', ':', 'g', '?', ')', '+', 'F', '{', 's', '5', ',', 'L', '`', '%', 'a', '<', '\\', "'", 'T']
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
print(f"chars: {chars}")
print(f"key : {key}")
# ENCRYPT
plain_text = input("Enter a message to encrypt: ")
cipher_text = ""
for letter in plain_text:
index = chars.index(letter)
cipher_text += key[index]
print(f"original message : {plain_text}")
print(f"encrypted message: {cipher_text}")
# Enter a message to encrypt: I like pizza!
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', 'R', ']', 'u', 'H', '/', 'l', 'z', 'c', ';', 'p', '_', 'M', '#', 'T', '4', '1', '2', '3', '0', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'y', 'L', 'x', 'n', 'o', 'p', 'q', 'r', 's', 't', 'A', 'v', 'W', 'X', 'Z', 't', 'J', 'C', 'P', 'Q', 'U', 'E', 'F', 'I', 'D', 'N', 'B', 'y', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# Enter a message to encrypt: I like pizza!
# original message : I like pizza!
# encrypted message: D Liye piJJa9
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
# print(f"chars: {chars}")
# print(f"key : {key}")
# ENCRYPT
plain_text = input("Enter a message to encrypt: ")
cipher_text = ""
for letter in plain_text:
index = chars.index(letter)
cipher_text += key[index]
print(f"original message : {plain_text}")
print(f"encrypted message: {cipher_text}")
# DECRYPT
cipher_text = input("Enter a message to decrypt: ")
plain_text = ""
for letter in cipher_text:
index = key.index(letter)
plain_text += chars[index]
print(f"encrypted message: {cipher_text}")
print(f"original message : {plain_text}")
# Enter a message to encrypt: I like pizza!
# original message : I like pizza!
# encrypted message: NkLiyekpiJJa9
# Enter a message to decrypt: NkLiyekpiJJa9
# encrypted message: NkLiyekpiJJa9
# original message : I like pizza!
44. ⭐ hangman game 🕺
# Hangman in Python
import random
words = ("apple", "orange", "banana", "coconut", "pineapple")
# dictionary of key:()
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
# print(hangman_art[3])
# (' o ', '/| ', ' ')
for line in hangman_art[3]:
print(line)
# o
# /|
#
import random
words = ("apple", "orange", "banana", "coconut", "pineapple")
# dictionary of key:()
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
def display_man(wrong_guesses):
print("**********")
for line in hangman_art[wrong_guesses]:
print(line)
print("**********")
def display_hint(hint):
pass
def display_answer(answer):
pass
def main():
answer = random.choice(words)
# print(answer)
# apple
hint = ["_"] * len(answer)
# print(hint)
# ['_', '_', '_', '_', '_']
wrong_guesses = 6
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
guess = input("Enter a letter: ").lower()
if __name__ == '__main__':
main()
# **********
# o
# /|\
# / \
# **********
# Enter a letter:
# wordslist.py
words = ("apple", "orange", "banana", "coconut", "pineapple")
# main.py
from wordslist import words
import random
# dictionary of key:()
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
def display_man(wrong_guesses):
print("**********")
for line in hangman_art[wrong_guesses]:
print(line)
print("**********")
def display_hint(hint):
print(" ".join(hint))
def display_answer(answer):
print(" ".join(answer))
def main():
answer = random.choice(words)
hint = ["_"] * len(answer)
wrong_guesses = 0
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
guess = input("Enter a letter: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("Invalid input")
continue
if guess in guessed_letters:
print(f"{guess} is already guessed")
continue
guessed_letters.add(guess)
if guess in answer:
for i in range(len(answer)):
if answer[i] == guess:
hint[i] = guess
else:
wrong_guesses += 1
if "_" not in hint:
display_man(wrong_guesses)
display_answer(answer)
print("YOU WIN!")
is_running = False
elif wrong_guesses >= len(hangman_art) - 1:
display_man(wrong_guesses)
display_answer(answer)
print("YOU LOSE!")
is_running = False
if __name__ == '__main__':
main()
# **********
#
#
#
# **********
# _ _ _ _ _ _ _ _ _
# Enter a letter: p
# **********
#
#
#
# **********
# p _ _ _ _ p p _ _
# Enter a letter: &
# Invalid input
# **********
#
#
#
# **********
# p _ _ _ _ p p _ _
# Enter a letter: i
# **********
#
#
#
# **********
# p i _ _ _ p p _ _
# Enter a letter: n
# **********
#
#
#
# **********
# p i n _ _ p p _ _
# Enter a letter: p
# p is already guessed
# **********
#
#
#
# **********
# p i n _ _ p p _ _
# Enter a letter: x
# **********
# o
#
#
#
# **********
# p i n _ _ p p _ _
# Enter a letter: z
# **********
# o
# |
#
# **********
# p i n _ _ p p _ _
# Enter a letter: e
# **********
# o
# |
#
# **********
# p i n e _ p p _ e
# Enter a letter: a
# **********
# o
# |
#
# **********
# p i n e a p p _ e
# Enter a letter: l
# **********
# o
# |
#
# **********
# p i n e a p p l e
# YOU WIN!
45. python object oriented programming 🚗
object = A “bundle” of related attributes (variables) and methods (functions) Ex. phone, cup, book You need a “class” to create many objects
class = (blueprint) used to design the structure and layout of an object
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
car1 = Car("Mustang", 2024, "red", False)
print(car1)
# <__main__.Car object at 0x000001AE490AE610>
print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
def drive(self):
print("You drive the car")
def stop(self):
print("You stop the car")
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
car1.drive()
# You drive the car
car2.drive()
# You drive the car
car1.stop()
# You stop the car
car2.stop()
# You stop the car
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
def drive(self):
print(f"You drive the {self.color} {self.model}")
def stop(self):
print(f"You stop the {self.color} {self.model}")
def describe(self):
print(f"{self.year} {self.color} {self.model}")
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
car1.drive()
# You drive the red Mustang
car1.stop()
# You stop the red Mustang
car1.describe()
# 2024 red Mustang
46. class variables 🎓
class variables = Shared among all instances of a class Defined outside the constructor Allow you to share data among all objects created from that class
class Car:
wheels = 4 # class variables
def __init__(self, model, year):
self.model = model # instance variable
self.year = year # instance variables
class Student:
class_year = 2024
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
print(student1.name)
print(student1.age)
# Spongebob
# 30
print(student1.class_year)
print(student2.class_year)
print(Student.class_year)
# 2024
# 2024
# 2024
class Student:
class_year = 2024
num_students = 0
def __init__(self, name, age):
self.name = name
self.age = age
Student.num_students += 1
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
student3 = Student("Squidward", 35)
student4 = Student("Sandy", 35)
print(Student.num_students)
# 4
print(f"My graduating class of {Student.class_year} has {Student.num_students} students")
print(student1.name)
print(student2.name)
print(student3.name)
print(student4.name)
# My graduating class of 2024 has 4 students
# Spongebob
# Patrick
# Squidward
# Sandy
47. inheritance 👨👦👦
Inheritance = Allows a class to inherit attributes and methods from another class
Helps with code reusability and extensibility
class Child(Parent)
class Sub(Super)
class Father:
height = 182
color = "pink"
class Son(Father):
pass
class Animal:
def __init__(self, name):
self.name = name
self.is_alive = True
def eat(self):
print(f"{self.name} is eating")
def sleep(self):
print(f"{self.name} is asleep")
class Dog(Animal):
pass
class Cat(Animal):
pass
class Mouse(Animal):
pass
dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")
print(dog.name)
print(dog.is_alive)
dog.eat()
dog.sleep()
# Scooby
# True
# Scooby is eating
# Scooby is asleep
class Animal:
def __init__(self, name):
self.name = name
self.is_alive = True
def eat(self):
print(f"{self.name} is eating")
def sleep(self):
print(f"{self.name} is sleeping")
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Mouse(Animal):
def speak(self):
print("SQUEEK!")
dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")
dog.speak()
# WOOF!
48. multiple inheritance 🐟
multiple inheritance = inherit from more than one parent class
C(A, B)
multiple inheritance = inherit from a parent which inherits from another parent
C(B) <- B(A) <- A
class Prey:
pass
class Predator:
pass
class Rabbit:
pass
class Hawk:
pass
class Fish:
pass
class Prey:
def flee(self):
print("This animal is fleeing")
class Predator:
def hunt(self):
print("This animal is hunting")
class Rabbit(Prey):
pass
class Hawk(Predator):
pass
class Fish(Prey, Predator):
pass
rabbit = Rabbit()
hawk = Hawk()
fish = Fish()
rabbit.flee()
# This animal is fleeing
rabbit.hunt()
# AttributeError: 'Rabbit' object has no attribute 'hunt'
hawk.hunt()
# This animal is hunting
hawk.flee()
# AttributeError: 'Hawk' object has no attribute 'flee'
fish.flee()
# This animal is fleeing
fish.hunt()
# This animal is hunting
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
def sleep(self):
print(f"{self.name} is sleeping")
class Prey(Animal):
def flee(self):
print(f"{self.name} is fleeing")
class Predator(Animal):
def hunt(self):
print(f"{self.name} is hunting")
class Rabbit(Prey):
pass
class Hawk(Predator):
pass
class Fish(Prey, Predator):
pass
rabbit = Rabbit("Bugs")
hawk = Hawk("Tony")
fish = Fish("Nemo")
rabbit.eat()
# Bugs is eating
rabbit.sleep()
# Bugs is sleeping
rabbit.flee()
# Bugs is fleeing
hawk.flee()
# AttributeError: 'Hawk' object has no attribute 'flee'
hawk.eat()
# Tony is eating
hawk.hunt()
# Tony is hunting
fish.eat()
fish.sleep()
fish.flee()
fish.hunt()
# Nemo is eating
# Nemo is sleeping
# Nemo is fleeing
# Nemo is hunting
49. super() 🔴
super() = Function used in a child class to call methods from a parent class (superclass).
Allows you to extend the functionality of the inherited methods
class Super: # 👨🏻
pass
class Sub(Super): # 👶🏻
pass
class super
class super(type, object_or_type=None)
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
The object_or_type determines the method resolution order to be searched. The search starts from the class right after the type.
class Circle:
def __init__(self, color, is_filled, radius):
self.color = color
self.is_filled = is_filled
self.radius = radius
class Square:
def __init__(self, color, is_filled, width):
self.color = color
self.is_filled = is_filled
self.width = width
class Triangle:
def __init__(self, color, is_filled, width, height):
self.color = color
self.is_filled = is_filled
self.width = width
self.height = height
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
print(circle.color)
print(circle.is_filled)
print(f"{circle.radius}cm")
# red
# True
# 5cm
print(square.color)
print(square.is_filled)
print(f"{square.width}cm")
# blue
# False
# 6cm
print(triangle.color)
print(triangle.is_filled)
print(f"{triangle.width}cm")
print(f"{triangle.height}cm")
# yellow
# True
# 7cm
# 8cm
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
def describe(self):
print(f"It is {self.color} and {'filled' if self.is_filled else 'not filled'}")
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
circle.describe()
# It is red and filled
square.describe()
# It is blue and not filled
triangle.describe()
# It is yellow and filled
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
def describe(self):
print(f"It is {self.color} and {'filled' if self.is_filled else 'not filled'}")
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
def describe(self):
super().describe()
print(f"It is a circle with an area of {3.14 * self.radius * self.radius}cm^2")
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
def describe(self):
super().describe()
print(f"It is a square with an area of {self.width * self.width}cm^2")
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
def describe(self):
super().describe()
print(f"It is a triangle with an area of {self.width * self.height / 2}cm^2")
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
circle.describe()
# It is red and filled
# It is a circle with an area of 78.5cm^2
square.describe()
# It is blue and not filled
# It is a square with an area of 36cm^2
triangle.describe()
# It is yellow and filled
# It is a triangle with an area of 28.0cm^2
50. polymorphism 🎭
Polymorphism = Greek word that means to “have many forms or faces”
Poly = Many
Morphe = Form
TWO WAYS TO ACHIEVE POLYMORPHISM
1. Inheritance = An object could be treated of the same type as a parent class
2. “Duck typing” = Object must have necessary attributes/methods
class Shape:
pass
class Circle(Shape):
pass
class Square(Shape):
pass
class Triangle(Shape):
pass
circle = Circle()
square = Square()
triangle = Triangle()
shapes = [Circle(), Square(), Triangle()]
from abc import ABC, abstractmethod
class Shape:
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
shapes = [Circle(4), Square(5), Triangle(6, 7)]
for shape in shapes:
print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²
(How to add superscript ²):
Windows: Alt + 0178
Mac: Control + Command + Space
from abc import ABC, abstractmethod
class Shape:
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
class Pizza:
def __init__(self, topping, radius):
self.topping = topping
self.radius = radius
shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("pepperoni", 15)]
for shape in shapes:
print(f"{shape.area()}cm²")
# AttributeError: 'Pizza' object has no attribute 'area'
# 50.24cm²
# 25cm²
# 21.0cm²
from abc import ABC, abstractmethod
class Shape:
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
class Pizza(Circle):
def __init__(self, topping, radius):
super().__init__(radius)
self.topping = topping
shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("pepperoni", 15)]
for shape in shapes:
print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²
# 706.5cm²
51. duck typing 🦆
“Duck typing” = Another way to achieve polymorphism besides Inheritance
Object must have the minimum necessary attributes/methods
“If it looks like a duck and quacks like a duck, it must be a duck.”
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
def horn(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
# AttributeError: 'Car' object has no attribute 'speak'
# WOOF!
# MEOW!
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
def speak(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
print(animal.alive)
# AttributeError: 'Car' object has no attribute 'alive'
# WOOF!
# True
# MEOW!
# True
# HONK!
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
alive = False
def speak(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
print(animal.alive)
# WOOF!
# True
# MEOW!
# True
# HONK!
# False
52. static methods ⚡
Static methods = A method that belong to a class rather than any object from that class (instance)
Usually used for general utility functions
Instance methods = Best for operations on instances of the class (objects)
# INSTANCE METHOD
def get_info(self):
return f"{self.name} = {self.position}"
Static methods = Best for utility functions that do not need access to class data
@staticmethod
def km_to_miles(kilometers):
return kilometers * 0.621371
class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def get_info(self):
return f"{self.name} = {self.position}"
@staticmethod
def is_valid_position():
valid_positions = ["Manager", "Cashier", "Cook", "Janitor"]
return position in valid_positions
print(Employee.is_valid_position("Cook"))
# True
print(Employee.is_valid_position("Rocket Scientist"))
# False
class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def get_info(self):
return f"{self.name} = {self.position}"
@staticmethod
def is_valid_position():
valid_positions = ["Manager", "Cashier", "Cook", "Janitor"]
return position in valid_positions
employee1 = Employee("Eugune", "Manager")
employee2 = Employee("Squidward", "Cashier")
employee3 = Employee("Spongebob", "Cook")
print(Employee.is_valid_position("Rocket Scientist"))
# False
print(employee1.get_info())
print(employee2.get_info())
print(employee3.get_info())
# Eugune = Manager
# Squidward = Cashier
# Spongebob = Cook
53. class methods 🏫
Class methods = Allow operations related to the class itself
Take (cls) as the first parameter, which represents the class itself.
Instance methods = Best for operations on instances of the class (objects)
Static methods = Best for utility functions that do not need access to class data
Class methods = Best for class-level data or require access to the class itself
class Student:
count = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
# INSTANCE METHOD
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"Total # of students: {cls.count}"
print(Student.get_count())
# Total # of students: 0
class Student:
count = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
# INSTANCE METHOD
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"Total # of students: {cls.count}"
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)
print(Student.get_count())
# Total # of students: 3
class Student:
count = 0
total_gpa = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
Student.total_gpa = gpa
# INSTANCE METHOD
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"Total # of students: {cls.count}"
@classmethod
def get_average_gpa(cls):
if cls.count == 0:
return 0
else:
return f"Average gpa: {cls.total_gpa / cls.count.2f}"
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)
print(Student.get_count())
# Total # of students: 3
print(Student.get_average_gpa())
# Average gpa: 3.07
54. magic methods 🌟
Magic methos = Dunder methods (double underscore) init, str, eq
They are automatically called by many of Python’s built-in operations.
They allow developers to define or customize the behavior of objects
class Student:
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
def __str__(self):
return f"name: {self.name} gpa: {self.gpa}"
def __eq__(self, other):
return self.name == other.name
def __gt__(self, other):
return self.gpa > other.gpa
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
print(student1)
print(student1 == student2)
print(student1 > student2)
# name: Spongebob gpa: 3.2
# False
# True
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print(book1)
# <__main__.Book object at 0x000001E78F76EE50>
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
book4 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print(book1)
# 'The Hobbit' by J.R.R. Tolkien
print(book3 == book4)
# False
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
book4 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 17222)
print(book1)
# 'The Hobbit' by J.R.R. Tolkien
print(book3 == book4)
# True
print(book2 < book3)
# TypeError: '<' not supported between instances of 'Book' and 'Book'
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
book4 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 17222)
print(book2 < book3)
# False
print(book2 > book3)
# True
print(book2 + book3)
# TypeError: unsupported operand type(s) for +: 'Book' and 'Book'
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} pages"
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
book4 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 17222)
print(book2 + book3)
# 395 pages
print("Lion" in book3)
# TypeError: argument of type 'Book' is not iterable
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} pages"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print("Lion" in book3)
# True
print("Lion" in book1)
# False
print("Rowling" in book2)
# True
print("Rowling" in book3)
# False
print(book1['title'])
# TypeError: 'Book' object is not subscriptable
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} pages"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print(book1['title'])
# The Hobbit
print(book2['title'])
# Harry Potter and The Philosopher's Stone
print(book3['title'])
# The Lion, the Witch and the Wardrobe
print(book3['author'])
# None
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} pages"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
elif key == "author":
return self.author
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print(book3['author'])
# C.S. Lewis
print(book2['author'])
# J.K. Rowling
print(book1['author'])
# J.R.R. Tolkien
print(book1['num_pages'])
# None
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"'{self.title}' by {self.author}"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} pages"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
elif key == "author":
return self.author
elif key == "num_pages":
return self.num_pages
else:
return f"Key '{key}' was not found"
book1 = Book("The Hobbit", "J.R.R. Tolkien", 310)
book2 = Book("Harry Potter and The Philosopher's Stone", "J.K. Rowling", 223)
book3 = Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis", 172)
print(book1['num_pages'])
# 310
print(book2['num_pages'])
# 223
print(book3['num_pages'])
# 172
print(book3['audio'])
# Key 'audio' was not found
55. @property ⚙️
property = Decorator used to define a method as a property (it can be accessed like an attribute)
Benefit: Add additional logic when read, write, or delete attributes
Gives you getter, setter, and deleter method
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
pass
@property
def height(self):
pass
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3.0cm
# 4.0cm
print(rectangle._width)
print(rectangle._height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("Width must be greater than zero")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("Height must be greater than zero")
rectangle = Rectangle(3, 4)
rectangle.width = 0
rectangle.height = -1
print(rectangle.width)
print(rectangle.height)
# Width must be greater than zero
# Height must be greater than zero
# 3.0cm
# 4.0cm
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("Width must be greater than zero")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("Height must be greater than zero")
rectangle = Rectangle(3, 4)
rectangle.width = 5
rectangle.height = 6
print(rectangle.width)
print(rectangle.height)
# 5.0cm
# 6.0cm
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("Width must be greater than zero")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("Height must be greater than zero")
@width.deleter
def width(self):
del self._width
print("Width has been deleted")
@height.deleter
def height(self):
del self._height
print("Height has been deleted")
rectangle = Rectangle(3, 4)
rectangle.width = 5
rectangle.height = 6
del rectangle.width
def rectangle.height
# Width has been deleted
# Height has been deleted
56. decorators 🎊
Decorator = A function that extends the behavior of another function
w/o modifying the base function
Pass the base function as an argument to the decorator
@add_sprinkles
get_ice_cream(“vanilla”)
def get_ice_cream():
print("Here is your ice cream 🍨")
get_ice_cream()
# Here is your ice cream 🍨
def add_sprinkles(func):
def wrapper():
func() # print("Here is your ice cream 🍨")
return wrapper
@add_sprinkles
def get_ice_cream():
print("Here is your ice cream 🍨")
get_ice_cream()
# Here is your ice cream 🍨
def add_sprinkles(func):
def wrapper():
print("*You add sprinkles 🎊*")
func()
return wrapper
@add_sprinkles
def get_ice_cream():
print("Here is your ice cream 🍨")
get_ice_cream()
# *You add sprinkles 🎊*
# Here is your ice cream 🍨
def add_sprinkles(func):
print("*You add sprinkles 🎊*")
func()
@add_sprinkles
def get_ice_cream():
print("Here is your ice cream 🍨")
# *You add sprinkles 🎊*
# Here is your ice cream 🍨
def add_sprinkles(func):
def wrapper():
print("*You add sprinkles 🎊*")
func()
return wrapper
def add_fudge(func):
def wrapper():
print("*You add fudge 🍫*")
func()
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream():
print("Here is your ice cream 🍨")
get_ice_cream()
# *You add sprinkles 🎊*
# *You add fudge 🍫*
# Here is your ice cream 🍨
def add_sprinkles(func):
def wrapper():
print("*You add sprinkles 🎊*")
func()
return wrapper
def add_fudge(func):
def wrapper():
print("*You add fudge 🍫*")
func()
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
print(f"Here is your {flavo}ice cream 🍨")
get_ice_cream("vanilla")
# TypeError: add_sprinkles.<locals>.wrapper() takes 0 positional arguments bet 1 was given
def add_sprinkles(func):
def wrapper(*args, **kwargs):
print("*You add sprinkles 🎊*")
func(*args, **kwargs)
return wrapper
def add_fudge(func):
def wrapper(*args, **kwargs):
print("*You add fudge 🍫*")
func(*args, **kwargs)
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
print(f"Here is your {flavo}ice cream 🍨")
get_ice_cream("vanilla")
# *You add sprinkles 🎊*
# *You add fudge 🍫*
# Here is your vanilla ice cream 🍨
57. exception handling 🚦
exception = An event that interrupts the flow of a program
(ZeroDivisionError, TypeError, ValueError)
1.try, 2.except, 3.finally
1 / 0
# ZeroDivisionError: division by zero
1 + "1"
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
int("pizza")
# ValueError: invalid literal for int() with base 10: 'pizza'
try:
# Try some code
except Exception:
# Handle an Exception
finally:
# Do some clean up
number = int(input("Enter a number: "))
print(1 / number)
# Enter a number: 0
# ZeroDivisionError: division by zero
# Enter a number: pizza
# ValueError: invalid literal for int() with base 10: 'pizza'
try:
number = int(input("Enter a number: "))
print(1 / number)
except ZeroDivisionError:
print("You can't divide by zero IDIOT!")
except ValueError:
print("Enter only numbers please!")
# Enter a number: 0
# You can't divide by zero IDIOT!
# Enter a number: pizza
# Enter only numbers please!
try:
number = int(input("Enter a number: "))
print(1 / number)
except ZeroDivisionError:
print("You can't divide by zero IDIOT!")
except ValueError:
print("Enter only numbers please!")
except Exception: # Too broad exception clause
print("Something went wrong!")
finally:
print("Do some cleanup here")
# Enter a number: 0
# You can't divide by zero IDIOT!
# Do some cleanup here
# Enter a number: 1
# 1.0
# Do some cleanup here
There are many different types of exceptions, you can always look under the official python documentation for an extensive list and well everybody that’s exception handling in Python.
58. file detection 🕵️♂️
<!-- test.txt -->
like pizza
# main.py
import os
file_path = "test.txt"
if os.path.exists(file_path):
print(f"The location '{file_path}' exists")
else:
print("That location doesn't exist")
# The location 'test.txt' exists
# main.py
import os
file_path = "test.txt"
if os.path.exists(file_path):
print(f"The location '{file_path}' exists")
if os.path.isfile(file_path):
print("That is a file")
elif os.path.isdir(file_path):
print("That is a directory")
else:
print("That location doesn't exist")
# The location 'test.txt' exists
# That is a file
59. writing files ✍
Python writing files (.txt, .json, .csv)
txt_data = "I like pizza!"
file_path = "output.txt"
with open(file_path, "w") as file:
file.write(txt_data)
print(f"txt file '{file_path}' was created")
# txt file 'output.txt' was created
# <!-- output.txt -->
# I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "x") as file:
file.write(txt_data)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# That file already exists!
<!-- output.txt -->
I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write(txt_data)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# txt file 'output.txt' was created
# <!-- output.txt -->
# I like pizza!I like pizza!
<!-- output.txt -->
I like pizza!I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write(txt_data)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# txt file 'output.txt' was created
# <!-- output.txt -->
# I like pizza!
<!-- output.txt -->
I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write("\n" + txt_data)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# txt file 'output.txt' was created
# <!-- output.txt -->
# I like pizza!
# I like pizza!
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
file.write(employees)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# TypeError: write() argument must be str, not list
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
for employee in employees:
file.write(employee)
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# txt file 'output.txt' was created
# <!-- output.txt -->
# EugeneSquidwardSpongebobPatrick
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
for employee in employees:
file.write(employee + "\n")
print(f"txt file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# txt file 'output.txt' was created
# <!-- output.txt -->
# Eugene
# Squidward
# Spongebob
# Patrick
import json
employee = {
"name": "Spongebob",
"age": 30,
"job": "cook"
}
file_path = "output.json"
try:
with open(file_path, "w") as file:
json.dump(employee, file)
print(f"json file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# json file 'output.txt' was created
# <!-- output.json -->
# {"name": "Spongebob", "age": 30, "job": "cook"}
import json
employee = {
"name": "Spongebob",
"age": 30,
"job": "cook"
}
file_path = "output.json"
try:
with open(file_path, "w") as file:
json.dump(employee, file, indent=4)
print(f"json file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# json file 'output.txt' was created
# <!-- output.json -->
# {
# "name": "Spongebob",
# "age": 30,
# "job": "cook"
# }
import json
import csv
employees = [["Name", "Age", "Job"],
["Spongebob", 30, "Cook"],
["Patrick", 37, "Unemployed"],
["Sandy", 27, "Scientist"]]
file_path = "output.csv"
try:
with open(file_path, "w") as file:
writer = csv.writer(file)
for row in employees:
writer.writerow(row)
print(f"csv file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# csv file 'output.txt' was created
# <!-- output.csv -->
# Name,Age,Job
#
# Spongebob,30,Cook
#
# Patrick,37,Unemployed
#
# Sandy,27,Scientist
import json
import csv
employees = [["Name", "Age", "Job"],
["Spongebob", 30, "Cook"],
["Patrick", 37, "Unemployed"],
["Sandy", 27, "Scientist"]]
file_path = "output.csv"
try:
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
for row in employees:
writer.writerow(row)
print(f"csv file '{file_path}' was created")
except FileExistsError:
print("That file already exists!")
# csv file 'output.txt' was created
# <!-- output.csv -->
# Name,Age,Job
# Spongebob,30,Cook
# Patrick,37,Unemployed
# Sandy,27,Scientist
60. reading files 🔍
Python reading files (.txt, .json, csv)
<!-- input.txt -->
I like pizza!
It's really good!
// input.json
{
"name": "Spongebob",
"age": 30,
"job": "cook"
}
<!-- input.csv -->
Name,Age,Job
Spongebob,30,Cook
Patrick,37,Unemployed
Sandy,27,Scientist
file_path = "input.txt"
with open(file_path, "r") as file:
content = file.read()
print(content)
# I like pizza!
# It's really good!
The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try…except..finally usage patterns to be encapsulated for convenient reuse.
import json
file_path = "input.json"
try:
with open(file_path, "r") as file:
content = json.load(file)
print(content)
print(content["name"])
except FileNotFoundError:
print("That file was not found")
except PermissionError:
print("You do not have permission to read that file")
# {"name": "Spongebob", "age": 30, "job": "cook"}
# Spongebob
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
print(content)
except FileNotFoundError:
print("That file was not found")
except PermissionError:
print("You do not have permission to read that file")
# <_csv.reader object at 0x0000017D81C4EAA0>
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
for line in content:
print(line)
except FileNotFoundError:
print("That file was not found")
except PermissionError:
print("You do not have permission to read that file")
# ['Name', 'Age', 'Job']
# ['Spongebob', '30', 'Cook']
# ['Patrick', '37', 'Unemployed']
# ['Sandy', '27', 'Scientist']
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
for line in content:
print(line[0])
except FileNotFoundError:
print("That file was not found")
except PermissionError:
print("You do not have permission to read that file")
# Name
# Spongebob
# Patrick
# Sandy
61. dates & times 📅
import datetime
date = datetime.date(2025, 1, 2)
print(date)
# 2025-01-02
today = datetime.date.today()
print(today)
# 2025-05-02
time = datetime.time(12, 30, 0)
print(time)
# 12:30:00
now = datetime.datetime.now()
print(now)
# 2025-05-02 09:41:55.409676
now = now.strftime("%H %M %S")
print(now)
# 09 41 55
now = now.strftime("%H:%M:%S")
print(now)
# 09:41:55
now = now.strftime("%H:%M:%S %m-%d-%Y")
print(now)
# 09:41:55 05-02-2025
Directive | Meaning | Example | Notes |
---|---|---|---|
%a |
Weekday as locale’s abbreviated name. | Sun, Mon, …, Sat (en_US); So, Mo, …, Sa (de_DE) |
(1) |
%A |
Weekday as locale’s full name. | Sunday, Monday, …, Saturday (en_US); Sonntag, Montag, …, Samstag (de_DE) |
(1) |
%w |
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. | 0, 1, …, 6 | |
%d |
Day of the month as a zero-padded decimal number. | 01, 02, …, 31 | (9) |
%b |
Month as locale’s abbreviated name. | Jan, Feb, …, Dec (en_US); Jan, Feb, …, Dez (de_DE) |
(1) |
%B |
Month as locale’s full name. | January, February, …, December (en_US); Januar, Februar, …, Dezember (de_DE) |
(1) |
%m |
Month as a zero-padded decimal number. | 01, 02, …, 12 | (9) |
%y |
Year without century as a zero-padded decimal number. | 00, 01, …, 99 | (9) |
%Y |
Year with century as a decimal number. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (2) |
There are many different format codes you can use with strftime
. You can always look under the Python strftime Documentation for a comprehensive list and explanations.
import datetime
date = datetime.date(2025, 1, 2)
today = datetime.date.today()
time = datetime.time(12, 30, 0)
now = datetime.datetime.now()
now = now.strftime("%H:%M:%S %m-%d-%Y")
target_datetime = datetime.datetime(2030, 1, 2, 12, 12, 30, 1)
curren_datetime = datetime.datetime.now()
if target_datetime < curren_datetime:
print("Target date has passed")
else:
print("Target date has NOT passed")
# Target date has NOT passed
62. ⭐ alarm clock ⏰
# Python Alarm Clock
import time
import datetime
import pygame # pip install pygame
def set_alarm(alarm_time): # ex. "23:00:00"
pass
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# pygame 2.6.0 (SDL 2.28.4, Python 3.12.5)
# Hello from the pygame community. https://www.pygame.org/contribute.html
👆"This functionality implementation can be found in the pygame library's initialization file (/.venv/Lib/site-packages/pygame/init.py lines 338-342)."
# Enter the alarm time (HH:MM:SS): 09:00:00
# Alarm set for 09:00:00
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
is_running = True
while is_running:
curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(curren_datetime)
is_running = False
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Enter the alarm time (HH:MM:SS): 10:00:00
# Alarm set for 10:00:00
# 09:42:16
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
is_running = True
while is_running:
curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(curren_datetime)
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Enter the alarm time (HH:MM:SS): 10:00:00
# Alarm set for 10:00:00
# 09:42:16
# 09:42:17
# 09:42:18
# ...
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
is_running = True
while is_running:
curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(curren_datetime)
if curren_datetime == alarm_time:
print("WAKE UP! ")
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Enter the alarm time (HH:MM:SS): 09:45:00
# Alarm set for 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# WAKE UP!
# Process finished with exit code 0
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
is_running = True
while is_running:
curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(curren_datetime)
if curren_datetime == alarm_time:
print("WAKE UP! ")
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
pygame.mixer.music.play()
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Enter the alarm time (HH:MM:SS): 09:45:00
# Alarm set for 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# WAKE UP!
# Process finished with exit code 0
Module pygame.mixer
: pygame module for loading and playing sounds
# pygame.mixer
def init(frequency: int = 44100,
size: int = -16,
channels: int = 2,
buffer: int = 512,
devicename: str | None = None,
allowedchanges: int = 5) -> None
# Python Alarm Clock
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
sound_file = "my_music.mp3"
is_running = True
while is_running:
curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(curren_datetime)
if curren_datetime == alarm_time:
print("WAKE UP! ")
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time.sleep(1)
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("Enter the alarm time (HH:MM:SS): ")
set_alarm(alarm_time)
# Enter the alarm time (HH:MM:SS): 09:45:00
# Alarm set for 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# WAKE UP!
👆That’s how to create an alarm clock in Python.
63. multithreading 🧵
multithreading = Used to perform multiple tasks concurrently (multithreading)
Good for I/O bound tasks like reading files or fetching data from APIs
threading.Thread(target=my_function)
import threading
import time
def walk_dog():
time.sleep(8)
print("You finish walking the dog")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
walk_dog()
take_out_trash()
get_mail()
# You finish walking the dog
# You take out the trash
# You get the mail
import threading
import time
def walk_dog():
time.sleep(8)
print("You finish walking the dog")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
chore1 = threading.Thread(target=walk_dog)
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("All chores are complete!")
# All chores are complete!
# You take out the trash
# You get the mail
# You finish walking the dog
import threading
import time
def walk_dog():
time.sleep(8)
print("You finish walking the dog")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
chore1 = threading.Thread(target=walk_dog)
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("All chores are complete!")
chore1.join()
chore2.join()
chore3.join()
# You take out the trash
# You get the mail
# You finish walking the dog
# All chores are complete!
import threading
import time
def walk_dog(first):
time.sleep(8)
print(f"You finish walking {first}")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
# interpreted as a string enclosed in parentheses
chore1 = threading.Thread(target=walk_dog, args=("Scooby",))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("All chores are complete!")
chore1.join()
chore2.join()
chore3.join()
# You take out the trash
# You get the mail
# You finish walking Scooby
# All chores are complete!
import threading
import time
def walk_dog(first):
time.sleep(8)
print(f"You finish walking {first}")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
# interpreted as a string enclosed in parentheses
chore1 = threading.Thread(target=walk_dog, args=("Scooby"))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("All chores are complete!")
chore1.join()
chore2.join()
chore3.join()
# TypeError: walk_dog() takes 1 positional argument but 6 were given
# You take out the trash
# You get the mail
# You finish walking Scooby
# All chores are complete!
import threading
import time
def walk_dog(first, last):
time.sleep(8)
print(f"You finish walking {first} {last}")
def take_out_trash():
time.sleep(2)
print("You take out the trash")
def get_mail():
time.sleep(4)
print("You get the mail")
# interpreted as a string enclosed in parentheses
chore1 = threading.Thread(target=walk_dog, args=("Scooby", "Doo"))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("All chores are complete!")
chore1.join()
chore2.join()
chore3.join()
# You take out the trash
# You get the mail
# You finish walking Scooby Doo
# All chores are complete!
64. request API data ↩️
PokéAPI
ex. https://pokeapi.co/api/v2/pokemon/pikachu
# How to connect to an API using Python
import requests # pip install requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
pass
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
print(response)
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# <Response [200]>
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
print("Data retrieved!")
else:
print(f"Failed to retrieve data {response.status_code}")
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# Data retrieved!
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
pokemon_data = response.json()
print(pokemon_data)
else:
print(f"Failed to retrieve data {response.status_code}")
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# {
# "abilities": [
# {
# "ability": {
# "name": "static",
# "url": "https://pokeapi.co/api/v2/ability/9/"
# },
# "is_hidden": false,
# "slot": 1
# },
# {
# "ability": {
# "name": "lightning-rod",
# "url": "https://pokeapi.co/api/v2/ability/31/"
# },
# "is_hidden": true,
# "slot": 3
# }
# ],
# "base_experience": 112,
# "height": 4,
# "id": 25,
# "name": "pikachu",
# "types": [
# {
# "slot": 1,
# "type": {
# "name": "electric",
# "url": "https://pokeapi.co/api/v2/type/13/"
# }
# }
# ],
# "weight": 60
# }
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
pokemon_data = response.json()
return pokemon_data
else:
print(f"Failed to retrieve data {response.status_code}")
pokemon_name = "pikachu"
pokemon_info = get_pokemon_info(pokemon_name)
if pokemon_info:
print(f"Name: {pokemon_info['name'].capitalize()}")
print(f"Id: {pokemon_info['id']}")
print(f"Height: {pokemon_info['height']}")
print(f"Weight: {pokemon_info['weight']}")
# Name: Pikachu
# Id: 25
# Height: 4
# Weight: 60
65. PyQt5 GUI intro 🖥️
Graphical User Interface
# PyQt5 introduction
import sys
# pip install PyQt5
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
def main():
pass
if __name__ == '__main__':
main()
sys
— System-specific parameters and functions
This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
if __name__ == '__main__':
main()
#
# Process finished with exit code 0
sys.argv
The list of command line arguments passed to a Python script. argv[0]
is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c
command line option to the interpreter, argv[0]
is set to the string '-c'
. If no script name was passed to the Python interpreter, argv[0]
is the empty string.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QIcon
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My cool first GUI")
self.setGeometry(700, 300, 500, 500)
# self.setGeometry(x, y, width, height)
self.setWindowIcon(QIcon("profile_pic.jpg"))
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
66. PyQt5 labels 🏷️
# PyQt5 QLabels
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("Hello", self) # (window will be a parent widget)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("Hello", self)
label.setFont(QFont("Arial", 40))
label.setGeometry(0, 0, 500, 100)
label.setStyleSheet("color: #1fff5a;"
"background-color: #6fdcf7;"
"font-weight: bold;"
"font-style: italic;"
"text-decoration: underline;") # Google search for "color picker"
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("Hello", self)
label.setFont(QFont("Arial", 40))
label.setGeometry(0, 0, 500, 100)
label.setStyleSheet("color: #1fff5a;"
"background-color: #6fdcf7;"
"font-weight: bold;"
"font-style: italic;"
"text-decoration: underline;")
# label.setAlignment(Qt.AlignTop) # VERTICALLY TOP
# label.setAlignment(Qt.AlignBottom) # VERTICALLY BOTTOM
# label.setAlignment(Qt.AlignVCenter) # VERTICALLY CENTER
# label.setAlignment(Qt.AlignRight) # HORIZONTALLY RIGHT
# label.setAlignment(Qt.AlignHCenter) # HORIZONTALLY CENTER
# label.setAlignment(Qt.AlignLeft) # HORIZONTALLY LEFT
# label.setAlignment(Qt.AlignHCenter | Qt.AlignTop) # CENTER & TOP
# label.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) # CENTER & BOTTOM
# label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) # CENTER & CENTER
label.setAlignment(Qt.AlignCenter) # CENTER & CENTER
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
67. PyQt5 images 📷
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel(self)
label.setGeometry(0, 0, 250, 250)
# label.setGeometry(x, y, width, height)
pixmap = QPixmap("profile_pic.jpg")
label.setPixmap(pixmap)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel(self)
label.setGeometry(0, 0, 250, 250)
# label.setGeometry(x, y, width, height)
pixmap = QPixmap("profile_pic.jpg")
label.setPixmap(pixmap)
label.setScaledContents(True)
label.setGeometry((self.width() - label.width()) // 2,
(self.height() - label.height()) // 2,
label.width(),
label.height())
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
68. PyQt5 layout managers 🧲
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel,
QWidget, QVBoxLayout, QHBoxLayout, QGridLayout)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.initUI()
def initUI(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
label1 = QLabel("#1", self)
label2 = QLabel("#2", self)
label3 = QLabel("#3", self)
label4 = QLabel("#4", self)
label5 = QLabel("#5", self)
label1.setStyleSheet("background-color: red;")
label2.setStyleSheet("background-color: yellow;")
label3.setStyleSheet("background-color: green;")
label4.setStyleSheet("background-color: blue;")
label5.setStyleSheet("background-color: purple;")
# vbox = QVBoxLayout()
# vbox.addWidget(label1)
# vbox.addWidget(label2)
# vbox.addWidget(label3)
# vbox.addWidget(label4)
# vbox.addWidget(label5)
# central_widget.setLayout(vbox)
# hbox = QHBoxLayout()
# hbox.addWidget(label1)
# hbox.addWidget(label2)
# hbox.addWidget(label3)
# hbox.addWidget(label4)
# hbox.addWidget(label5)
# central_widget.setLayout(hbox)
grid = QGridLayout()
grid.addWidget(label1, 0, 0)
grid.addWidget(label2, 0, 1)
grid.addWidget(label3, 1, 0)
grid.addWidget(label4, 1, 1)
grid.addWidget(label5, 2, 2)
central_widget.setLayout(grid)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
69. PyQt5 buttons 🛎️
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.initUI()
def initUI(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.button = QPushButton("Click me!", self)
self.initUI()
def initUI(self):
self.button.setGeometry(150, 200, 200, 100)
self.button.setStyleSheet("font-size: 30px;")
self.button.clicked.connect(self.on_click)
def on_click(self):
print("Button clicked!")
self.button.setText("Clicked!")
self.button.setDisabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.button = QPushButton("Click me!", self)
self.label = QLabel("Hello", self)
self.initUI()
def initUI(self):
self.button.setGeometry(150, 200, 200, 100)
self.button.setStyleSheet("font-size: 30px;")
self.button.clicked.connect(self.on_click)
self.label.setGeometry(150, 300, 200, 100)
self.label.setStyleSheet("font-size: 50px;")
def on_click(self):
self.label.setText("Goodbye")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
70. PyQt5 checkboxes ✅
71. PyQt5 radio buttons 🔘
72. PyQt5 line edits 💬
73. PyQt5 CSS styles 🎨
74. ⭐ digital clock program 🕒
75. ⭐ stopwatch program ⏱
76. ⭐ weather API app ☀️