PYTHON
Python Basics
A structured collection of my Python lessons.
# Module: Branching Statements
# Part 1
#----------------TASK_1---------------#
# The user types in three numbers.
# The program prints the sum or product of these numbers based on the user's choice.
num_1=float(input("Number 1: "))
num_2=float(input("Number 2: "))
num_3=float(input("Number 3: "))
choose=str(input("What you want to do? (Sum / Product)")).lower()
if choose == "sum":
print(num_1+num_2+num_3)
elif choose =="product":
print(num_1*num_2*num_3)
else:
print("wrong")
#----------------TASK_2---------------#
# The user types in three numbers.
# Based on the user's choice, the program prints a maximum of three,
# a minimum of three, or arithmetic mean of three numbers.
number_1=float(input("Your first number: "))
number_2=float(input("Your seccond number: "))
number_3=float(input("Your third number: "))
option=str(input("What you want to do? (Max/Min/Mean)")).lower()
# (Note for me )Burada biz LIST kimi də edə bilərik məsələn
# əgər istifadəçi 5 dəyər əlavə edərsə o zaman bizim sistem çökməməlidir
if option =="max":
print("Maximum is:", max(number_1, number_2, number_3))
elif option == "min":
print("Minimum is:", min(number_1,number_2,number_3))
elif option == "mean":
mean = (number_1 + number_2 + number_3)/3
print("Mean is:", mean)
else:
print("Wrong")
# ----------------TASK_3---------------#
# The user types in the number of meters.
# Based on the user's choice, the program converts meters to miles, inches, or yards.
value = float(input("Add your value (Only Meters): "))
option_2 = input("Choose your option (mile / inch / yard): ").lower()
if option_2 == "mile":
print(value , " Meters equal to = ",value * 0.000621371," miles" )
elif option_2 == "inch":
print(value , " Meters equal to = ",value * 39.3701," inches")
elif option_2 == "yard":
print(value , " Meters equal to = ",value * 1.09361," yards")
else:
print("Wrong")
# Module: Branching Statements
# Part 1
#----------------TASK_1---------------#
# The user types in three numbers.
# The program prints the sum or product of these numbers based on the user's choice.
num_1 = float(input("Add first number: "))
num_2 = float(input("Add second number: "))
num_3 = float(input("Add third number: "))
choose = input("Selrct one option (Sum/product): ").lower()
if choose == "sum":
result = num_1 + num_2 + num_3
print("Your sum is: ", result)
elif choose == "product":
result_2 = num_1 * num_2 * num_3
print("Your product is: ", result_2)
else:
print("Please use normal value!")
#----------------TASK_2---------------#
# Task 2
# The user types in three numbers.
# Based on the user's choice, the program prints a maximum of three,
# a minimum of three, or arithmetic mean of three numbers.
number_1 = float(input("Add first number: "))
number_2 = float(input("Add second number: "))
number_3 = float(input("Add third number: "))
option = input("Choose (Max/Min/Mean): ").lower()
if option == "max":
result = max(number_1, number_2, number_3)
print("Your max is: ", result)
elif option == "min":
result = min(number_1, number_2, number_3)
print("Your min is: ",result)
elif option == "mean":
result = (number_1 + number_2 + number_3) / 3
print("Your mean is: ", result)
else:
print("Invalid option!")
#----------------TASK_3---------------#
# The user types in the number of meters.
# Based on the user's choice, the program converts meters to miles, inches, or yards.
value = float(input("White your value in meters: "))
option = input("Choose (Miles/Inches/Yards): ").lower()
if option == "miles":
result = value * 0.000621371
print("Your value in miles is: ", result)
elif option == "inches":
result = value * 39.3701
print("Your value in inches is: ", result)
elif option == "yards":
result = value * 1.09361
print("Your value in yards is: ", result)
else:
print("Invalid option!")
# Module: Loops
# Part 4
#----------------TASK_1---------------#
# The user types in two numbers (start and end points of the range).
# Analyze all the numbers in this range as follows: if the number is a multiple of 7, print it.
first = int(input("Add your first number here: "))
second = int(input("Add your second number here: "))
for i in range (first, second + 1):
if i % 7 == 0:
print("There are the numbers: ", i)
#----------------TASK_2---------------#
# The user types in two numbers (start and end points of the range).
# Analyze all the numbers in this range. Print the following:
# All numbers in the range;
# All numbers in the range in descending order;
# All numbers that are multiples of 7;
# How many numbers are multiples of 5.
num_1 = int(input("First number: "))
num_2 = int(input("Second number: "))
print("All numbers in the range:")
for i in range (num_1, num_2 +1):
print(i)
print("All numbers in the range in descending order: ")
for i in range(num_2, num_1 -1, -1): # (Note for me) tərsdən sayın edərkən buna diqqət et.
print(i)
print("All numbers that are multiples of 7: ")
for i in range (num_1, num_2 +1):
if i % 7 ==0:
print(i)
count = 0
print("How many numbers are multiples of 5: ")
for i in range(num_1, num_2 +1):
if i % 5== 0:
count += 1
print(count)
#----------------TASK_3---------------#
#The user types in two numbers (start and end points of the range).
# Analyze all the numbers in this range.
# The output should be according to the rules specified below.
#If the number is a multiple of 3 (divisible by 3 without remainder),
# print the word Fizz.
# If it is a multiple of 5, print Buzz. If it is a multiple of 3 and 5, print Fizz Buzz.
# If the number is not a multiple of 3 or 5, print the number itself.
start = int(input("First: "))
end = int(input("Last: "))
for number in range(start, end + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizz Buzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
# Module Loops
# Part 5
#----------------TASK_1---------------#
# The user types in two numbers.
# Find the sum of all even, odd numbers and
# multiples of 9 in the specified range, as well as arithmetic mean of each group.
start = int(input("First num: "))
end = int(input("Second num: "))
count_1 = 0
sum_1 = 0
print("Even numbers: ")
for i in range(start, end +1):
if i % 2 == 0:
count_1 += 1
sum_1 += i
print(i)
if count_1 != 0:
total_1 = sum_1 / count_1
print("Count: ",count_1)
print("Sum: ", sum_1)
print("Total: ",total_1)
#----------------------------
count_2 = 0
sum_2 = 0
print("Odd numbers: ")
for i in range(start, end +1):
if i % 2 != 0:
count_2 += 1
sum_2 += i
print(i)
if count_2 != 0:
total_2 = sum_2 / count_2
print("Count: ",count_2)
print("Sum: ", sum_2)
print("Total: ",total_2)
#-----------------------------
count_3 = 0
sum_3 = 0
print("Only 9: ")
for i in range(start, end +1):
if i % 9 == 0:
count_3 += 1
sum_3 += i
print(i)
if count_3 != 0:
total_3 = sum_3 / count_3
print("Count: ",count_3)
print("Sum: ", sum_3)
print("Total: ",total_3)
#----------------TASK_2---------------#
# The user types in the length of a line and a symbol to fill the line.
# Print a vertical line made out of the typed in symbol of the specified length.
#For instance, if the typed in number and symbol are 5 and %, the output will be as follows:
lenght = int(input("Add lenght: "))
symbol = input("Add yuour symbol: ")
for i in range (lenght):
print(symbol)
#----------------TASK_3---------------#
# The user types in numbers.
# If the number is greater than 0, print "Your number is positive";
# if it is less than zero, print "Your number is negative"; if it is equal to 0, print "Your number is equal to zero."
# When the user types in 7, the program stops and prints "Good bye!"
while True:
choose = float(input("Whrite any number here: "))
if choose == 7:
print("Good bye")
break
elif choose == 0:
print("Your number is zero")
elif choose > 0:
print("Your number is positive")
elif choose < 0:
print("Your number is negative")
#----------------TASK_4---------------#
# The user types in numbers.
# The program must calculate their sum and find the maximum and minimum.
# When the user types in 7, the program stops and prints "Good bye!".
# I GOT BIG HELP FOR TASK_4 FROM AI (SORRY)
sum = 0
max = None
min = None
while True:
value = float(input("Add some value: "))
if value == 7:
print("Good bye")
break
sum += value
if max is None or value > max:
max = value
if min is None or value < min:
min = value
print("Sum: ",sum)
print("Max: ", max)
print("Min: ", min)
# Module: Tuples, Sets, Dictionaries
# Part 2
#----------------TASK_1---------------#
# Create an app that stores information about great basketball players.
# Store the player's full name and height.
# Provide the possibility to add, delete, search, and replace data. Use a dictionary to store information.
players = {}
def add_player():
name = input("Enter full name of the player: ")
height = input("Enter player's height (cm): ")
players[name] = height
print(f"{name} was added.")
def delete_player():
name = input("Enter full name of the player: ")
if name in players:
del players[name]
print(name, "was deleted.")
else:
print("Player not found.")
def search_player():
name = input("Enter full name of the player: ")
if name in players:
print({name : players[name]})
else:
print("Not found")
def replace_player():
name = input("Enter full name of the player: ")
if name in players:
players[name] = input("Enter new height: ")
else:
print("Not found")
def show_players():
print(players)
while True:
print("1 - Add player")
print("2 - Delete player")
print("3 - Search player")
print("4 - Replace player height")
print("5 - Show all players")
choose = input("Choose: ")
if choose == "1":
add_player()
elif choose == "2":
delete_player()
elif choose == "3":
search_player()
elif choose == "4":
replace_player()
elif choose == "5":
show_players()
break
else:
print("Invalid choice")
#----------------TASK_2---------------#
# Create an app English-French Dictionary.
# Store a word in English and its French translation.
# Provide the possibility to add, delete, search, and replace data.
# Use a dictionary to store information.
dicrionary ={}
def add_word():
word = input("Enter English word: ")
translation = input("Enter French translation: ")
dicrionary[word] = translation
print("Word added")
def delete_word():
word = input("Delete word")
if word in dicrionary:
del dicrionary[word]
else:
print("Word not found")
def search_word():
word = input("Search word: ")
if word in dicrionary:
print(word)
else:
print("There are no such word in dictionary")
def replace_word():
word = input("Enter word to replace: ")
if word in dicrionary:
dicrionary[word] = input("Enter new word: ")
else:
print("Invalid")
def show_words():
print(dicrionary)
while True:
print("1. Add word")
print("2. Delete word")
print("3. Search word")
print("4. Replace word")
print("5. Show words")
option = input("Select: ")
if option == "1":
add_word()
elif option == "2":
delete_word()
elif option == "3":
search_word()
elif option == "4":
replace_word()
elif option == "5":
show_words()
break
else:
print("Invalid option")
#----------------TASK_3---------------#
# Create an app Company.
# Store the following information about a person:
# full name, phone number, corporate email, job title, room number, skype.
# Provide the possibility to add, delete, search, and replace data.
# Use a dictionary to store information.
company = {}
def add_employee():
name = input("Enter full name: ")
phone = input("Enter phone number: ")
email = input("Enter corporate email: ")
title = input("Enter job title: ")
room_number = input("Enter room number: ")
skype = input("Enter skype: ")
company[name] = {
"phone": phone,
"email": email,
"title": title,
"room": room_number,
"skype": skype
}
print("Employee added successfully")
def delete_employee():
name = input("Enter full name: ")
if name in company:
del company[name]
print("Employee deleted successfully")
else:
print("Employee not found")
def search_employee():
name = input("Enter full name: ")
if name in company:
print(company[name])
else:
print("invalid")
def replace_employee():
name = input("Enter full name: ")
if name in company:
print("What do you want to replace?")
phone = input("Enter new phone")
email = input("Enter the new email: ")
title = input("Enter the new job title: ")
room_number = input("Enter the new room number: ")
skype = input("Enter the new skype: ")
company[name] = {
"phone": phone,
"email": email,
"title": title,
"room": room_number,
"skype": skype
}
def show_all():
print(company)
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Replace employee")
print("5. Show all employees")
select = input("Select an option: ")
if select == "1":
add_employee()
elif select == "2":
delete_employee()
elif select == "3":
search_employee()
elif select == "4":
replace_employee()
elif select == "5":
show_all()
break
else:
print("Invalid")
#----------------TASK_4---------------#
# Create an app Book Collection.
# Store the following information about books:
# author, title, genre, year of release, publisher.
# Provide the possibility to add, delete, search, and replace data.
# Use a dictionary to store information.
book = {}
def add_book():
title = input("Enter the title of the book: ")
author = input("Enter the author of the book: ")
genre = input("Enter the genre of the book: ")
year = input("Enter the year of release: ")
publisher = input("Enter the publisher of the book: ")
book[title] = {
"title": title,
"author": author,
"genre": genre,
"year": year,
"publisher": publisher
}
print("Book added successfully")
def delete_book():
title = input("Enter the title of the book to delete: ")
if title in book:
del book[title]
print("Book deleted successfully")
else:
print("Book not found")
def search_book():
title = input("Enter the title of the book to search: ")
if title in book:
print(book[title])
else:
print("Book not found")
def replace_book():
title = input("Add title of book: ")
if title in book:
print("What do you want to replace?")
print("1. Author")
print("2. Genre")
print("3. Year")
print("4. Publisher")
choice = input("Enter your choice: ")
if choice == "1":
book[title]["author"] = input("Enter new author: ")
elif choice == "2":
book[title]["genre"] = input("Enter new genre: ")
elif choice == "3":
book[title]["year"] = input("Enter new year: ")
elif choice == "4":
book[title]["publisher"] = input("Enter new publisher: ")
else:
print("Invalid choice")
while True:
print("1. Add book")
print("2. Delete book")
print("3. Search book")
print("4. Replace book")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
add_book()
elif choice == "2":
delete_book()
elif choice == "3":
search_book()
elif choice == "4":
replace_book()
elif choice == "5":
break
else:
print("Invalid choice")
# Module: Functions
# Part 1
#----------------TASK_1---------------#
# Write a function that prints formatted text given below:
# "Don't compare yourself with anyone in this world...
# if you do so, you are insulting yourself."
# Bill Gates
def text_1():
print("Don't compare yourself with anyone in this world...")
print("if you do so, you are insulting yourself.")
print("Bill Gates")
def text_2():
print("The only limit to our realization of tomorrow is our doubts of today.")
print("— Franklin D. Roosevelt")
text_1()
print()
text_2()
#----------------TASK_2---------------#
# Write a function that takes two numbers as a parameter and displays all even numbers in between.
def even_numbers():
for i in range(x, y+1):
if i % 2 == 0:
print(i)
print("1. Even numbers between 1 and 100")
x = int(input("Please choose first value: "))
y = int(input("Please choose second value: "))
even_numbers()
#----------------TASK_3---------------#
# Write a function that prints an empty or solid square made out of some symbol.
# The function takes the following as parameters: the length of the side of the square, a symbol, and a boolean
# variable:
# if it is True, the square is solid;
# if False, the square is empty.
def square(size, symbol, solid):
if solid == True:
for i in range(size):
for j in range(size):
print(symbol, end=' ')
print()
else:
for i in range(size):
for j in range(size):
if i == 0 or i == -1 or j == 0 or j == -1:
print(symbol, end=' ')
else:
print(' ', end=' ')
# Something wrond maybe
size = int(input("Add size: "))
symbol = input("Add symbol: ")
solid_2 = input("Solid? (yes/no): ").lower()
solid = True if solid_2 == 'yes' else False
square(size, symbol, solid)
#----------------TASK_4---------------#
# Write a function that returns the smallest of five numbers.
# Numbers are passed as parameters.
def small_num(a,b,c,d,e):
return min(a,b,c,d,e)
a = int(input("A) "))
b = int(input("B) "))
c = int(input("C) "))
d = int(input("D) "))
e = int(input("E) "))
result = small_num(a,b,c,d,e)
print("small one ----> ",result)
#----------------TASK_5---------------#
def product_range(start,end):
if start > end:
start, end = end , start
result = 1
for i in range(start,end+1):
result *= i
return result
start = int(input("add num: "))
end = int(input("add secind num: "))
final = product_range(start,end)
print("Product: ", final)
#----------------TASK_6---------------#
def example_num(number):
return len(str(number))
number_a = int(input("Add num: "))
final_a = example_num(number_a)
print("How nuch number there: ", final_a)
#----------------TASK_7---------------#
def palindrome_number(number):
num_str = str(number)
return num_str == num_str[::-1]
num_b = int(input("enter: "))
if palindrome_number(num_b):
print("palindrome")
else:
print("not palindrome")
# Module: Functions
# Part 2
#----------------TASK_1---------------#
def list_product(numbers):
result = 1
for num in numbers:
result *= num
return result
numbers = input("Make by commas: ")
number_list = [int(i) for i in numbers.split(",")] # Note for me. (.split) Bir daha bax.
print("Product: ", list_product(number_list))
#----------------TASK_2---------------#
def find_min(list):
return min(list)
num_1 = int(input("Add 1th numbers: "))
num_2 = int(input("Add 2th numbers: "))
num_3 = int(input("Add 3th numbers: "))
num_4 = int(input("Add 4th numbers: "))
list = [num_1,num_2,num_3,num_4]
find_min(list)
print("Minimum number:", find_min(list))
#----------------TASK_3---------------#
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def count_primes_in_range(start, end):
count = 0
for num in range(start, end + 1):
if is_prime(num):
count += 1
return count
start = int(input("Add first: "))
end = int(input("Add last: "))
result = count_primes_in_range(start, end)
print("How many prime numbers are in range:", result)
#----------------TASK_4---------------#
def remove_target(numbers, target):
removed_count = numbers.count(target)
numbers = [num for num in numbers if num != target]
return removed_count, numbers
nums = [1, 3, 5, 3, 7, 3, 9]
target_num = 3
removed, new_list = remove_target(nums, target_num)
print("Removed count:", removed)
print("New list:", new_list)
#----------------TASK_5---------------#
def mix_list(list_1, list_2):
return list_1 + list_2
list_1 = [1,3,5,7]
list_2 = [2,4,6,8]
total = mix_list(list_1, list_2)
print("Mix list ", total)
# Module: Exceptions
# Part 1
#----------------TASK_1---------------#
try:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age < 0 or age > 130:
print("Invalid age")
else:
print(f"Hello, {name}! Your age is {age}")
except ValueError:
print("Please add correct info!")
#----------------TASK_2---------------#
# Exception inside here!
def user_welcome(name_2,age_2):
try:
age_2 = int(age_2)
if age_2 < 0 or age_2 > 130:
print("Invalid age")
else:
print(f"Hello, {name_2}! Your age is {age_2}")
except ValueError:
print("Invalid input")
name_2 = input("Enter your name: ")
age_2 = input("Enter your age: ")
info = user_welcome(name_2,age_2)
print(info)
# Exception not inside here!
def user_welcome(name_2,age_2):
if age_2 < 0 or age_2 > 130:
print("Invalid age")
else:
print(f"Hello, {name_2}! Your age is {age_2}")
try:
name_2 = input("Enter your name: ")
age_2 = int(input("Enter your age: "))
info = user_welcome(name_2,age_2)
print(info)
except ValueError:
print("Please add correct info!")
#----------------TASK_3---------------#
print("All numbers should be greater than 0!\n")
numbers = []
try:
while True:
user_input = input("Enter numbers or press (E) for exit: ")
if user_input.lower() == 'e':
break
number = int(user_input)
if number <= 0:
raise ValueError("Please enter number greater than 0!")
numbers.append(number)
print("Numbers:", numbers)
print("Sum of numbers:", sum(numbers))
except ValueError :
print("Error!")
#----------------TASK_4---------------#
# Exception inside the function!
def num_calc():
numbers = []
try:
while True:
user_input = input("Enter numbers or press (E) for exit: ")
if user_input.lower() == 'e':
break
number = int(user_input)
if number <= 0:
raise ValueError("Please enter number greater than 0!")
numbers.append(number)
print("Numbers:", numbers)
print("Sum of numbers:", sum(numbers))
except ValueError:
print("Error!")
num_calc()
# Exception not inside the function!
def num_calc():
numbers = []
while True:
user_input = input("Enter numbers or press (E) for exit: ")
if user_input.lower() == 'e':
break
number = int(user_input)
if number <= 0:
raise ValueError("Please enter number greater than 0!")
numbers.append(number)
return numbers
try:
result = num_calc()
print("Numbers:", result)
print("Sum of numbers:", sum(result))
except ValueError as ve:
print("Error!", ve)
except Exception:
print("Unexpected error occurred!")
a = int(input("Please add range: "))
list =[]
x,y = 0,1
for i in range(0,a):
list.append(x)
x,y=y,x+y
print(list)
while True:
def prime_number(num):
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def list_prime(func, n):
if n <= 1:
return "Add normal"
prime_list = []
for i in range(2, n + 1):
if func(i):
prime_list.append(i)
return prime_list
m = int(input("Add a number: "))
x = list_prime(prime_number, m)
print("Prime numbers list:", x)
#----------------------TASK_1--------------------
def fib_range(start, end):
x, y = 0, 1
while x <= end:
if x >= start:
yield x
x, y = y, x + y
for num in fib_range(5, 30):
print(num)
#----------------------TASK_2--------------------
list1 = [1, 4, 2]
list2 = [3, 6, 5, 5]
def sum_lists(l1, l2):
max_len = max(len(l1), len(l2))
for i in range(max_len):
a = l1[i] if i < len(l1) else 0
b = l2[i] if i < len(l2) else 0
yield a + b
for val in sum_lists(list1, list2):
print(val)
#----------------------TASK_3--------------------
nums = [1,2,3,4]
def square(x):
return x ** 2
def cube(x):
return x ** 3
def calculate(list_to_work, function_to_call):
result = []
for i in list_to_work:
result.append(function_to_call(i))
return result
print(calculate(nums, square))
print(calculate(nums, cube))
#----------------------TASK_4--------------------
def agency_a_format(func):
def wrapper():
result = func()
return f"agency_a_format: {result}"
return wrapper
def agency_b_format(func):
def wrapper():
result = func()
return result.replace("$","£")
return wrapper
@agency_a_format
@agency_b_format
def report():
return "Total revenue: $10000"
print(report())
#-------------------------TASK_1--------------------
def check_prime(n):
if n <= 1:
return False
for i in range(2,int(n**0.5)+1):
if n % i == 0:
return False
return True
def print_range(start,end):
for i in range(start,end+1):
if check_prime(i):
yield i
for prime in print_range(10, 30):
print(prime)
#-------------------------TASK_2--------------------
def is_armstrong(n):
digits = list(map(int, str(n)))
power = len(digits)
total = sum(d**power for d in digits)
return total == n
def armstrong_range(start, end):
for number in range(start, end + 1):
if is_armstrong(number):
yield number
for a in armstrong_range(100, 999):
print(a)
#-------------------------TASK_3--------------------
lst = [1,3,5,7,9]
def min_lst(num):
return min(num)
def max_lst(num):
return max(num)
def find_min_or_max(list_to_check, function_to_call):
return function_to_call(list_to_check)
print("Minimum:", find_min_or_max(lst, min_lst))
print("Maximum:", find_min_or_max(lst, max_lst))
#-------------------------TASK_4--------------------
def pizza_base():
return "Pizza with dough"
def margarita(func):
def wrapper():
return func() + " + tomato sauce + cheese"
return wrapper
def capricosa(func):
def wrapper():
return func() + " + tomato sauce + cheese + ham"
return wrapper
def four_cheeses(func):
def wrapper():
return func() + " + tomato sauce + cheese + cheese + cheese + cheese"
return wrapper
def hawaiian(func):
def wrapper():
return func() + " + tomato sauce + cheese + ham + pineapple"
return wrapper
def mushrooms(func):
def wrapper():
return func() + " + mushrooms"
return wrapper
def pepperoni(func):
def wrapper():
return func() + " + pepperoni"
return wrapper
def olives(func):
def wrapper():
return func() + " + olives"
return wrapper
choice = input("Choose pizza: margarita, capricosa, four_cheeses, hawaiian: (M)(C)(F)(H) ").lower()
if choice == "m":
pizza = margarita(pizza_base)
elif choice == "c":
pizza = capricosa(pizza_base)
elif choice == "f":
pizza = four_cheeses(pizza_base)
elif choice == "h":
pizza = hawaiian(pizza_base)
else:
pizza = pizza_base
extra_choice = input("Add extra? mushrooms, pepperoni, olives, none: (M)(P)(O)(N) ").lower()
if extra_choice == "m":
pizza = mushrooms(pizza)
elif extra_choice == "p":
pizza = pepperoni(pizza)
elif extra_choice == "o":
pizza = olives(pizza)
print("\nYour order:")
print(pizza())
# ----------------------Task_1----------------------
class Car:
def __init__(self,brand,model,speed):
self.brand = brand
self.speed = speed
self.model = model
def start(self,sound=None):
if sound is None:
print(f"Your {self.model} is starting")
else:
print(f"Your {self.model} is starting with: {sound}")
def drive(self,speed=None):
if speed is None:
print(f"Your {self.brand} {self.model} car is driving ")
else:
print(f"Your {self.brand} {self.model} car is driving {speed} km/h")
print("Task 1")
car_1 = Car("BMW","M5",2025)
car_1.start()
car_1.start("vir vir vir")
car_1.drive()
car_1.drive(180)
print()
# ----------------------Task_2----------------------
class Book:
def __init__(self,name,genre,page):
self.name = name
self.genre = genre
self.page = page
def start(self,smell=None):
if smell is None:
print(f"The book's have {self.page} pages")
else:
print(f"The book's smell is {smell} in the {self.page} pages")
def read(self,color=None):
if color is None:
print(f"The book {self.name} with {self.genre} genre of book is reading ")
else:
print(f"The book {self.name} with {self.genre} genre book have {self.page} with {color} color")
print("Task 2")
book_1 = Book("Crime and Punishment","Novel",450)
book_1.start()
book_1.start("like that")
book_1.read()
book_1.read("Red")
print()
# ----------------------Task_3----------------------
class Stadium:
def __init__(self,name):
self.name = name
def start(self,color=None):
if color is None:
print(f"The stadium name is {self.name}")
else:
print(f"The stadium color is {color}")
def match(self,rival_1 = None, rival_2 = None):
if rival_1 is None and rival_2 is None:
print(f"Match playing in the {self.name} stadium")
else:
print(f"Match started: {rival_1} vs {rival_2}")
print("Task 3")
match_1 = Stadium("Camp Nou")
match_1.start()
match_1.start("Red and Blue")
match_1.match()
match_1.match("Barcelona","Real Madrid")
#-------------------------------------Task_1---------------------------------
class Shape:
def __str__(self):
return f"{self.__class__.__name__} with area: {self.area()}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
class RightTriangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return (self.base * self.height) / 2
class Trapezoid(Shape):
def __init__(self,a,b,h):
self.a = a
self.b = b
self.h = h
def area(self):
return ((self.a + self.b) / 2) * self.h
rectangle = Rectangle(5,3)
print(rectangle)
circle = Circle(5)
print(circle)
rightTriangle = RightTriangle(5,4)
print(rightTriangle)
trapezoid = Trapezoid(2,3,5)
print(trapezoid)
#-------------------------------------Task_2---------------------------------
class Shape:
def __init__(self):
return int(self.area())
def __str__(self):
return f"{self.__class__.__name__} with area: {self.area()}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __str__(self):
return f"Rectangle: width={self.width}, height={self.height}, area={self.area()}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def __str__(self):
return f"Circle: Radius={self.radius}, area={self.area()}"
class RightTriangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return (self.base * self.height) / 2
def __str__(self):
return f"RightTriangle: width={self.base}, height={self.height}, area={self.area()}"
class Trapezoid(Shape):
def __init__(self,a,b,h):
self.a = a
self.b = b
self.h = h
def area(self):
return ((self.a + self.b) / 2) * self.h
def __str__(self):
return f"Trapezoid: width_1={self.a}, width_2={self.b}, height={self.h}, area={self.area()}"
rectangle = Rectangle(5,3)
print(rectangle)
circle = Circle(5)
print(circle)
rightTriangle = RightTriangle(5,4)
print(rightTriangle)
trapezoid = Trapezoid(2,3,5)
print(trapezoid)
#-------------------------------------Task_3---------------------------------
class Shape:
def __init__(self):
pass
def __str__(self):
pass
class Square(Shape):
def __init__(self, x, y, side):
self.x = x
self.y = y
self.side = side
def show(self):
print(self.x, self.y),
print(self.x + self.side, self.y),
print(self.x, self.y + self.side),
print(self.x + self.side, self.y + self.side)
def save(self):
with open("save.txt","w") as file:
file.write(f"Top Left: {self.x}, {self.y}\n")
file.write(f"Top Right: {self.x + self.side}, {self.y}\n")
file.write(f"Bottom Left: {self.x}, {self.y + self.side}\n")
file.write(f"Bottom Right: {self.x + self.side}, {self.y + self.side}\n")
def load(self):
with open("save.txt", "r") as file:
return file.read()
class Rectangle(Shape):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.heigh = height
def show(self):
print(self.x, self.y),
print(self.x + self.width, self.y),
print(self.x, self.y + self.heigh),
print(self.x + self.width, self.y + self.heigh)
def save(self):
with open("save.txt","w") as file:
file.write(f"Top Left: {self.x}, {self.y}\n")
file.write(f"Top Right: {self.x + self.width}, {self.y}\n")
file.write(f"Bottom Left: {self.x}, {self.y + self.heigh}\n")
file.write(f"Bottom Right: {self.x + self.width}, {self.y + self.heigh}\n")
def load(self):
with open("save.txt", "r") as file:
return file.read()
class Circle(Shape):
def __init__(self, cx, cy, radius):
self.cx = cx
self.cy = cy
self.radius = radius
def show(self):
print(f"Circle: center=({self.cx}, {self.cy}), radius={self.radius}")
def save(self):
with open("save.txt","w") as file:
file.write(f"Circle: center=({self.cx}, {self.cy}), radius={self.radius}")
def load(self):
with open("save.txt", "r") as file:
return file.read()
class Ellipse(Shape):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.heigh = height
def show(self):
print(f"Ellipse: top-left=({self.x}, {self.y}), width={self.width}, height={self.heigh}")
print(f"Center=({self.x + self.width/2}, {self.y + self.heigh/2})")
def save(self):
with open("save.txt","w") as file:
file.write(f"Ellipse: top-left=({self.x}, {self.y}), width={self.width}, height={self.heigh}")
file.write(f"Center=({self.x + self.width/2}, {self.y + self.heigh/2})")
def save_shapes(filename, shapes):
with open(filename, "w", encoding="utf-8") as f:
for s in shapes:
if isinstance(s, Square):
f.write(f"Square {s.x} {s.y} {s.side}\n")
elif isinstance(s, Rectangle):
f.write(f"Rectangle {s.x} {s.y} {s.width} {s.heigh}\n")
elif isinstance(s, Circle):
f.write(f"Circle {s.cx} {s.cy} {s.radius}\n")
elif isinstance(s, Ellipse):
f.write(f"Ellipse {s.x} {s.y} {s.width} {s.heigh}\n")
def load_shapes(filename):
shapes = []
with open(filename, "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split()
if not parts:
continue
t = parts[0]
nums = list(map(float, parts[1:]))
if t == "Square" and len(nums) == 3:
x, y, side = nums
shapes.append(Square(x, y, side))
elif t == "Rectangle" and len(nums) == 4:
x, y, w, h = nums
shapes.append(Rectangle(x, y, w, h))
elif t == "Circle" and len(nums) == 3:
cx, cy, r = nums
shapes.append(Circle(cx, cy, r))
elif t == "Ellipse" and len(nums) == 4:
x, y, w, h = nums
shapes.append(Ellipse(x, y, w, h))
return shapes
shapes_list = [
Square(2, 3, 5),
Rectangle(1, 1, 4, 6),
Circle(5, 5, 3),
Ellipse(0, 0, 7, 4)
]
save_shapes("shapes.txt", shapes_list)
loaded_list = load_shapes("shapes.txt")
for i in loaded_list:
i.show()
#--------------Task_1------------------------
nums = [4, -2, 3, 1, -5, 6, 2, -1, 0]
result = (sum(nums)) / len(nums)
if result > 0:
x = (len(nums) *2) // 3
else:
x = len(nums) //3
part = nums[0:x]
sorted_part = sorted(part)
nums[0:x] = sorted_part
nums[x:] =nums[x:][::-1]
print(nums)
#--------------Task_2------------------------
grades = []
for i in range(0,10):
grade = int(input("Add your grade: "))
if grade >= 0 or grade <= 12:
grades.append(grade)
else:
print("Please enter a grade between 0 and 12")
print()
print("------------Choices-------------")
print()
print("1. Show all your grades")
print("2. Take the exam again")
print("3. Check if you can get a scholarship")
print("4. Sort your grades")
print("5. Exit")
print()
choice = input("Enter your choice: ")
while True:
if choice == "1":
print()
print("--------------------------------")
print(grades)
print("--------------------------------")
print()
exit = int(input("Press 0 to exit: "))
if exit == 0:
break
elif choice == "2":
print()
# print("Press 0 to exit")
print("Which subject do you want to retake the exam? (replacing grade)")
subject = int(input("Enter the subject (1 to 12): "))
if 1 <= subject <= 10:
print()
print("Your current grade for this subject is: ", grades[subject-1])
print()
new_grade = int(input("Enter your new grade: "))
grades[subject-1] = new_grade
print()
print("Succesfully removed the old grade")
print()
print("--------------------------------")
print(grades)
print("--------------------------------")
else:
print("Please enter a subject between 1 and 12")
print()
elif choice == "3":
print("--------------------------------")
print(grades)
print("--------------------------------")
print("You need 10.7 agerage grade at least! ")
if sum(grades) / len(grades) >= 10.7:
print("Your average is: ",sum(grades) / len(grades))
print("You can get a scholarship!")
break
else:
print("Your average is: ",sum(grades) / len(grades))
print("You can't get a scholarship!")
print()
break
elif choice == "4":
choice = str(input("Ascending or Descending (A/D): ")).lower()
if choice == "a":
grades.sort()
print(grades)
elif choice == "d":
grades.sort(reverse=True)
print(grades)
else:
print("Invalid choice")
elif choice == "5":
print("Goodbye!")
break
#--------------Task_3------------------------
nums = [12,15,17,14,9,5,21,19]
n = len(nums)
for i in range(n-1):
swapped = False
for j in range(n-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = True
if not swapped:
break
print(nums)
def find_minimum(numbers):
if len(numbers) == 1:
return numbers[0]
rest_minimum = find_minimum(numbers[1:])
if numbers[0] < rest_minimum:
return numbers[0]
else:
return rest_minimum
my_list = [4, 5, 6, 7, 8]
print("minimum number is:", find_minimum(my_list))
def pizza_orders():
price = 0
size = input("Add a size: small / large / extra-large: ")
if size == "small":
price =10
elif size == "large":
price = 15
elif size == "extra-large":
price = 20
peperoni = input("Do you wanna add peperoni? (yes / no): ")
if peperoni == "yes":
price = price + 2
chesse = input("Do you wanna add cheese? (yes / no): ")
if chesse == "yes":
price = price + 1
tip = price * 0.1
final = price + tip
print("Your final bill is: $",final)
pizza_orders()