python3 -- nested while loop driven user input menu decision tree - python-3.x

I have been stumped on this one for too long and I need some help. I am trying to create a user input menu decision tree that will lead the user to the appropriate function call. I just cant seem to get the path to function correctly. I keep getting stuck in the second loop. I have tried many different logics and conditions but nothing has made it work. I created some simple code that I think clearly shows what I am trying to achieve...
def menu():
print("1. Selection 1")
print("2. Selection 2")
print("3. Quit")
def menu1():
print("1.Selection Function 1")
print("2.Selection Function 2")
print("3.Quit")
def menu2():
print("1.Selection Function 3")
print("2.Selection Funtion 4")
print("3.Quit")
def func_1():
print("Funtion_1")
def func_2():
print("Funtion_2")
def func_3():
print("Funtion_3")
def func_4():
print("Funtion_4")
if __name__ == '__main__':
menu()
selection=int
selection1=int
selection2=int
while (selection != 3):
selection==int(input("Please Select a Menu Option: "))
if selection == 1:
menu1()
while ((selection1 != 3)):
selection1==int(input("What Type of funtion Would You Like To execute: "))
if selection1 == 1:
func_1()
if selection1 == 2:
func_2()
if selection1 == 3:
sys.exit()
elif selection == 2:
menu2()
while ((selection2==int(input("What Other Type of Function Would You Like To execute: ")) != 3)):
if selection2 == 1:
func_3()
if selection2 == 2:
func_4()
if selection2 == 3:
sys.exit()
elif selection == 6:
sys.exit()

Looks like you need to break out of the while loop instead of doing sys.exit() in the inner loops. If you do sys.exit() on inner loops it will exit and won't come back to the outer menu option.
your this line selection==int(input("Please Select a Menu Option: ")) should be selection=int(input("Please Select a Menu Option: ")). == is used for comparison not for assignment. for assignment we use =
Here, is modified code which works as expected.
def menu():
print("1. Selection 1")
print("2. Selection 2")
print("3. Quit")
def menu1():
print("1.Selection Function 1")
print("2.Selection Function 2")
print("3.Quit")
def menu2():
print("1.Selection Function 3")
print("2.Selection Funtion 4")
print("3.Quit")
def func_1():
print("Funtion_1")
def func_2():
print("Funtion_2")
def func_3():
print("Funtion_3")
def func_4():
print("Funtion_4")
if __name__ == '__main__':
menu()
selection=int
selection1=int
selection2=int
while (selection != 3):
selection=int(input("Please Select a Menu Option: "))
if selection == 1:
menu1()
while ((selection1 != 3)):
selection1=int(input("What Type of funtion Would You Like To execute: "))
if selection1 == 1:
func_1()
if selection1 == 2:
func_2()
if selection1 == 3:
break
elif selection == 2:
menu2()
while (selection2 != 3):
selection2=int(input("What Other Type of Function Would You Like To execute: "))
if selection2 == 1:
func_3()
if selection2 == 2:
func_4()
if selection2 == 3:
break
elif selection == 6:
sys.exit()

You are comparing selection with integer. Where selection has datatype, it will false forever. Instead do this selection == type(3) and this won't solve your problem.
One more thing is, first line in while loop
selection==int(input("Please Select a Menu Option: "))
here you are comparing(==), not assigning value(=).
selection=int(input("Please Select a Menu Option: "))
use single equals to symbol.
You can't compare the numbers, so you won't get required results, loops will be same for all numbers. For that you need to store numbers in selection variable.
Ask for further queries.

Related

New to python. Menu option to "Go Back"

I'm racking my brain on this and I'm sure it's unnecessary. I've tried looking for the answer online but it's leading me nowhere.
I'm writing a simple menu script (probably not the nicest format). In prompt 2, 3, 4 I'm in need of an option to get back to the previous prompt. Based on what I've found I just keep looping myself into a bigger and bigger issue.
Here is what I have:
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_cluster = 'Outdoors'
elif user_input2 == "2":
user_selected_cluster = 'Gym'
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_cluster = 'AM'
elif user_input4 == "2":
user_selected_cluster = 'PM'
else:
print("Invalid option selected. Run script again.")
exit()
I've tried a variety of while loops and even turning these into functions, which to be honest, I don't have a complete grasp of.
Every solution has just ended up with me looping the prompt I'm on, looping the entire script, or ending the script after prompt_1
Honestly would prefer to learn it instead of someone doing it but I can't even find good videos that address the subject.
Python (like many other languages) does not have a go to option.
The "goto" statement, which allows for unconditional jumps in program flow, was considered to be a bad programming practice because it can lead to confusing and difficult-to-maintain code. Instead, Python uses structured control flow statements, such as if, for, and while loops, which encourage clear and organized code that is easy to understand and debug.
However, you can put the code into functions to achieve the same result, like this:
def main():
''' the main module '''
# have 3 attempts at each question, then move on.
for i in range(3):
x = action_01()
if x != 'invalid': break
for i in range(3):
x = action_02()
if x != 'invalid': break
for i in range(3):
x = action_03()
if x != 'invalid': break
for i in range(3):
x = action_04()
if x != 'invalid': break
def action_01():
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_02():
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_action = 'Outdoors'
elif user_input2 == "2":
user_selected_action = 'Gym'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_03():
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_04():
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_action = 'AM'
elif user_input4 == "2":
user_selected_action = 'PM'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
if __name__ == '__main__':
main()
Note, there are even more efficient ways, but this will be a good starting point for you.

exit(), conditionals, return or break on Python menu?

If we are doing a menu on python and the user selects option for finish the interaction. Is preferable to use exit(), conditionals, return or break?
Example with break, where we stop the infinite loop with the break:
def show_menu():
print('1. Pet kitten\n'
'0. Exit')
def start_app():
while True:
show_menu()
user_choice = input('Select an option: ')
if user_choice == '1':
pet()
elif user_choice == '0':
print('\nBye!')
break
else:
print('\nPlease select a number from the menu.')
start_app()
Example with exit(), where we use built-in function exit() for stop the execution of the script:
def show_menu():
print('1. Pet kitten\n'
'0. Exit')
def start_app():
while True:
show_menu()
user_choice = input('Select an option: ')
if user_choice == '1':
pet()
elif user_choice == '0':
print('\nBye!')
exit()
else:
print('\nPlease select a number from the menu.')
start_app()
Example with conditionals, where the while stops when the condition change:
def show_menu():
print('1. Pet kitten\n'
'0. Exit')
def start_app():
continue_ = True
while continue_:
show_menu()
user_choice = input('Select an option: ')
if user_choice == '1':
pet()
elif user_choice == '0':
print('\nBye!')
continue_ = False
else:
print('\nPlease select a number from the menu.')
start_app()
Example with return, where we finish the interaction returning a random value:
def show_menu():
print('1. Pet kitten\n'
'0. Exit')
def start_app():
continue_ = True
while continue_:
show_menu()
user_choice = input('Select an option: ')
if user_choice == '1':
pet()
elif user_choice == '0':
print('\nBye!')
return None
else:
print('\nPlease select a number from the menu.')
start_app()
It is worth noticing that your options fall into two categories, with one important difference between them.
On one hand, you can use break, return or a condition variable to break out of the loop and, eventually, return to the caller. Among these options, I'd say just pick whichever gives the cleanest code.
On the other hand, you can use exit() which ends the program there and then.
If you ever wish to use this as something other than a top-level menu, for example wrapped in a library to be used as a sub-menu of something else, you do not want the program to suddenly exit.
Generally, exit() is a rather big chunk of explosives, that should be treated with a bit of respect.
For example 1:
First give 4 space in line 2 so that the print function can stay into the show_menu() function and second define the #pet() function in line 11, otherwise you will get name error. Then put a break statement after line 11.
For example 3:
The while loop stop in line 15 when you define continue as False.
#HappyCoding

Python Nested If Then statement not seen in while loop

I am developing a menu application (CLI) and when user selects a number choice from the menu then the app does something different for each choice. But first I want to make sure they enter a valid number then do something. If not a valid number, then loop through menu. If number 9 is selected, exit the application. The problem is it doesn't seem to recognize my nested if then condition statements. It just sees the first if then condition and then loops through menu again without "doing something". How do I get it to recognize the nested if thens?
import datetime
import os
import pyfiglet
def main():
Banner()
menu()
def menu():
choice =int('0')
while choice !=int('9'):
print("1. Show the banner again")
print("2. View just a selected date range")
print("3. Select a date range and show highest temperature")
print("4. Select a date range and show lowest temperature")
print("5. Select a data range and show the highest rainfall")
print("6. Make a silly noise")
print("7. See this menu again")
print("9. QUIT the program")
choice = input ("Please make a choice: ")
if choice.isdigit():
print(int(choice))
if choice == 1:
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
elif choice == 2:
getWeather()
choice == 0
elif choice == 3:
print("Do Something 3")
elif choice == 4:
print("Do Something 4")
elif choice == 5:
print("Do Something 5")
elif choice == 6:
os.system( "say burp burp burp burpeeeeee. I love love love this menu application")
elif choice == 7:
print("Do Something 7")
elif choice == 8:
print("Do Something 8")
elif choice == 9:
print("***********************************************************************")
print("Goodbye! Program exiting.....")
print("***********************************************************************")
exit()
else:
print("Your choice is not an integer. Please try again")
print("")
continue
def Banner():
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
def getWeather():
weatherdata1 = print(input("What date would you like to start your weather data query with? Please enter the date in this format YYYYMMDD"))
weatherdata2 = print(input("What date would you like to end your weather data query with? Please enter the date in this format YYYYMMDD"))
print(weatherdata1)
print(weatherdata2)
main()
You have to convert your input to int like so:
choice = int(input ("Please make a choice: "))
or, you need to convert the choice to int when comparing. Like so:
if int(choice) == 1:
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
elif int(choice) == 2:
getWeather()
choice == 0
...

Python if statement with a user input (input()) not working (Python 3.7)

I am trying to create a menu here. The menu allows the user to enter options. There is also a validate function to check if the option the user input was valid or not.
def menu():
while True:
display_menu()
user_input = validate("Choose Option")
if user_input == 1:
pass
elif user_input == 2:
exit()
def display_menu():
print("1) Application")
print("2) Quit Application")
def validate1(q):
user_input = input(q)
if len(user_input) == 0:
return False
elif user_input != "1" or user_input != "2": # Error is likely here
print("Invalid option, please choose another option")
return False
else:
return user_input
When you run this code, you get:
1) Application
2) Quit Application
Choose Option
However after entering 1, the validate function thinks the input 1 is invalid and you get:
Invalid option, please choose another option
1) Application
2) Quit Application
Choose Option
This should not be the case as 1 should be valid. At first I thought that it was an error regarding the type of the variable user_input and I have tried to change it (from line 22):
elif user_input != 1 or user_input != 2:
However the error still persists.
What is the error here?
elif user_input != "1" or user_input != "2":
lets, assume that your user input is "1" then that will make this statement true as
user_input (1) is not equal to (2)
Therefore you need to change that statement to something else like this :
def validate(q):
user_input = input(q)
if len(user_input) == 0:
return False
if user_input == str(1) or user_input == str(2): # Valid Options
return user_input
else:
print("Invalid option, please choose another option")
return False

How do I clear the screen in Python 3?

Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.
It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()

Resources