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
47. inheritance 👨👦👦
48. multiple inheritance 🐟
49. super() 🔴
50. polymorphism 🎭
51. duck typing 🦆
52. static methods ⚡
53. class methods 🏫
54. magic methods 🌟
55. @property ⚙️
56. decorators 🎊
57. exception handling 🚦
58. file detection 🕵️♂️
59. writing files ✍
60. reading files 🔍
61. dates & times 📅
62. ⭐ alarm clock ⏰
63. multithreading 🧵
64. request API data ↩️
65. PyQt5 GUI intro 🖥️
66. PyQt5 labels 🏷️
67. PyQt5 images 📷
68. PyQt5 layout managers 🧲
69. PyQt5 buttons 🛎️
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 ☀️