Functions
Functions are snippets of code that can be reused.
functions.py
def get_menu_option(): option = input(f'${balance} A)dd Money S)ubtract Money Q)uit:') return option def get_money(): money = input('Enter amount:') return int(money) def add_money(): # you need access to the global balance global balance print('Add money') money = get_money() balance = balance + money def subtract_money(): # you need access to the global balance global balance print('Subtract money') money = get_money() balance = balance - money def invalid_option(): print('Invalid option, try again') balance = 0 # do the while loop forever while True: option = get_menu_option() match option: case 'a': add_money() case 's': subtract_money() case 'q': # exit the while loop break case default: invalid_option() print("Done.")
Output:
$0 A)dd Money S)ubtract Money Q)uit:a Add money Enter amount:10 $10 A)dd Money S)ubtract Money Q)uit:s Subtract money Enter amount:20 $-10 A)dd Money S)ubtract Money Q)uit:a Add money Enter amount:30 $20 A)dd Money S)ubtract Money Q)uit:q Done.
The balance variable needs to be marked as global inside functions so that it can update it. If you don't do this then you will get an error.
Links
Exercises (5 mins)
-
Create functions for each of the case statements.
find_a_number.py
# create get_menu_option # create add_pet function # create remove_pet function # create list_all_pets function list_of_pets = [] # do the while loop forever while True: option = input(f'{len(list_of_pets)} A)dd Pet R)emove Pet L)ist pets Q)uit:') match option: case 'a': pet_name = input('Enter pet name to add:') list_of_pets.append(pet_name) case 'r': pet_name = input('Enter pet name to remove:') list_of_pets.remove(pet_name) case 'l': for pet in list_of_pets: print(pet) case 'q': # exit the while loop break case default: print('Invalid option, try again')
Output:
0 A)dd Pet R)emove Pet L)ist pets Q)uit:a Enter pet name to add: tootsie 1 A)dd Pet R)emove Pet L)ist pets Q)uit:a Enter pet name to add: fido 2 A)dd Pet R)emove Pet L)ist pets Q)uit:l tootsie fido 2 A)dd Pet R)emove Pet L)ist pets Q)uit:r Enter pet name to remove: fido 1 A)dd Pet R)emove Pet L)ist pets Q)uit:q Done.