Task: Create a simple text-based menu with three options: Greet the user. Calculate and print the user's age. Exit the program.
This is the final code. The documentation of this code is written below.
""" Text Based Menu:
Skapa en enkel textbaserad meny med tre alternativ:
1 Hälsa på användaren.
2 Skriv ut användarens ålder.
3 Avsluta programmet.
"""
name = input("Type your name: ")
print(f'Please choose from our 3 choices {name}.')
def text_menu(): # menu function to show the menu.
print(f"[1] Greet {name}.")
print(f"[2] Print {name}'s age")
print(f"[3] Quit {name}'s program")
return int(input("Choose an option")) # User input here as an integer in the text_menu() function.
def greet():
print(f'Hello! {name}.') # function "greet" to greet user.
def age():
print(f'What year were you born {name}?') # Calculate age (2023 - year input)
year = int(input())
age = 2023 - year
print(f'{name} is {age} years old.')
def quit():
print("Goodbye!")
while True: #continue to execute loop while "True"
choice = text_menu() # assign choice variable to text_menu() results.
if choice == 1: #Performs the greet() function.
greet()
elif choice == 2: # Performs the age() function.
age()
elif choice == 3: #Exits program
quit()
break
else:
print("Try again. Please choose an option")
This is a new concept. So I did some research.
Text-based menu in Python means “menu-driven program is a type of computer program which accepts the input from the user by showing a list of options. And users have to select any of the options to perform any operation.”
Source: Menu Driven Program in Python [Program With Explanation] (learnprogramo.com)
Source: https://www.geeksforgeeks.org/how-to-use-while-true-in-python/
Step 1: First sketch of code.
I noticed there are codes implemented to make a text-based menu: def function, while True statement, if, Elif, else statements. I want to make the menu personal so I use the f strings to print the user’s name every time in the code.
Make “name” the variable for the user input. The code will ask the user “Type your name.” After inputting the user name, Python will print in the Python Shell.
“Please choose from our 3 choices {name} in an f string format.
Why use the def function?
Readability: it’s easier to read my code if it is defined in a single function.
Functionality: it’s easier to know the purpose of Options 1, 2 and 3 as the text menus.
Maintainability: it’s easier to change my code later without affecting all my code.
Use the def function a lot for this code to make the options perform the actions. On the 1st code block, create text_menu() as a def function. Don’t forget to use : to tell Python the next codes will be local variables for the text_menu function. Also using f strings for {name} within the print statements.
Under the text_menu() code block, create 3 options:
[1] Greet user.
[2] Calculate the user's age.
[3] Exit Program
Create choice_from_user(): it will be the variable for the user choice input. Typecast the input into an integer since the choices will be either 1, 2 or 3, which Python must not read as strings.
Output:
Let’s say I choose 2. An error is made as the object is not callable, therefore, another def function must be created again. Let’s try that.
Make a def function here with (). It seems an: is expected before the int.
Output: The while True, if and elif functions have some errors…
If 1, 2 or 3 (other numbers as well) are chosen, the code yields the else statement: “Try again. Please choose the option”, which is wrong. It does not act.
As seen below, option 2 is chosen by the user, however, the loop goes back to the text_menu() function instead of age calculation.
Step 2: Make def functions per option. Fix the code within the if and elif statements to perform the def function in the while loop expression.
Each option must be able to perform an action assigned to it and not only print.
The text_menu() stays the same code because in the while True loop, the menu should be shown every time unless the else statement becomes True.
choice = choice_from_user() stays the same code because it’s the variable for the user input: [1], [2], or [3]. So, the problem might be in the if choice == (“1”), if choice == (“2”) and if choice == (“3”).
The mistake in this code is within the while loop. The print(variable strings) and age calculations inside the while loop do not work. Meaning, that Python does not perform the action asked by the user here. Instead, create another 3 different def functions OUTSIDE THE WHILE LOOP and USE THOSE INSIDE THE WHILE EXPRESSIONS.
This is the current code below with an error.
Step 2.1: Create the greet() function to greet the user. This will be an option [1].
The code will perform the actions if I assign a function per menu option.
Then, using the defined greet() function, nest the code in the if choice == 1: local variable block.
Step 2.2: Create the age() function to calculate the user’s age. This will be an option [2].
Cut the previous code from the elif statement and create an age() function.
Under this code block, fix the indentation of the variables year, age and print.
Assign the user’s age in the year variable, typecast it as an integer,
create another age variable, which subtracts 2023 - year.
Use an f string to code the {name} and {age}, and print.
Assign the age() function to elif choice == 2:
This means, that if 2 is chosen, the code will calculate the user’s age.
Step 2.3: Create the quit() function to exit the program. This will be an option [3].
Create another def function named quit() to print the strings “Goodbye.”
Use a break to stop the while loop repetition when [3] is chosen.
Step 2.4: The else statement will stay the same because it has worked before.
This code works if other numbers besides [1], [2] or [3] are chosen. Else statement is used when the if = False and elif = False.
Step 3: Let’s run the program again. Debugging.
Error. It did not work. From the output below, choices [1], [2] and [3] still do not perform the assigned def functions.
Change some codes in 2 different code blocks. The first is in the text_menu() function. Delete the choice_from_user and write it inside the text_menu() function. Instead of print, call with the return. These changes are made because the user’s input will always be included and required in the text_menu() function.
The second solution is the most difficult to fix.
Old code:
New code:
Since the choice_from_user() is deleted, there is no need to assign the variable choice to it. Remember that the user input is within the text_menu() function. Therefore, assign the text_menu() function to the choice variable instead.
Importantly, remember 3 different functions are created for 3 different options. The choice variable is within the every if and elif statements, assigned respectively. Here, it is now possible to tell each statement to perform an action based on the user input [1], [2] or [3].
Final Output with no errors: