New to python. Menu option to "Go Back" - python-3.x

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.

Related

How do I stop a program when the user types "No"?

I am a complete newbie and was trying to make a number magic trick. I want the program to stop when the user types "No". Here is my code below!
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
else:
print("Invalid Input")
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
else:
print("Invalid input")
You don't have to raise an error, you could simply use the exit method instead:
if x.strip().lower() == "no":
print("You said no!")
exit(0)
You could even use the exit method from the sys module, like this:
import sys
if x.strip().lower() == "no":
print("You said no!")
sys.exit(0)
INFO: The 0 in the exit method's parenthesis means that "this program finished without any errors" but replacing the 0 with a 1 would mean that "something went wrong with the program" and it's exiting with an error.
Good luck.
You could raise an exception. Also, it's good practice to put one-line if/else statements on the same line... For example,
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
raise SystemExit()
else:
print("Invalid Input")
raise SystemExit()
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
raise SystemExit()
else:
print("Invalid input")
raise SystemExit()
You're welcome to use this code...
if x == "No":
quit()
OR
from sys import exit
if x == "No":
exit()

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()

python3 -- nested while loop driven user input menu decision tree

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.

How to simplify elif in Python

I don't have a lot of experience with python but I think this can be much simpler. If anything available for the same result. Using a dictionary mapping to functions instead of all those elif maybe?
choice = input("Select an option: ")
if choice == "1":
try:
new_contact = create_contact()
except NotAPhoneNumberException:
print("The phone number entered is invalid, creation aborted!")
else:
contacts[new_contact['name']] = new_contact
save_contacts(contacts, filename)
elif choice == "2":
print_contact()
elif choice == "3":
search = input("Please enter name (case sensitive): ")
try:
print_contact(contacts[search])
except KeyError:
print("Contact not found")
elif choice == "0":
print("Ending Phone Book.\nHave a nice day!")
break
else:
print("Invalid Input! Try again.")

Resources