How to make program go back to the "menu"? - python

Done = False
while not Done:
print('S Start New Order')
print('E Edit Order')
print('P Print Bill')
print('R Receive Payment')
print('M Manager Report')
print('Q Quit')
print('-----------------')
Command = ''
while Command == '':
Command = input("Enter Choice> ")
Command = Command.strip().upper()
if Command[0] == 'S':
print('Start New Order:')
elif Command[0] == 'E':
print('Edit Order:')
elif Command[0] == 'P':
print('Print Bill:')
elif Command[0] == 'R':
print('Recieve Payment:')
elif Command[0] == 'M':
print('Manager Report:')
elif Command[0] == 'Q':
print('Quit:')
I want to make it so when someone types for instance "j" or "34", it jumps back to "Enter Choice" and does not display the whole menu all over again.

We have to check in entered value.
e.g.
while Command not in ['S', 'E','P', 'R', 'M', 'Q']:
Command = raw_input("Enter Choice> ")
Command = Command.strip().upper()
Use break statement when user enter Q option of Menu. or set value of Done = True
e.g.
elif Command[0] == 'Q':
print('Quit:')
break
OR
elif Command[0] == 'Q':
print('Quit:')
Done = True

Get rid of lines 1 and 2 since "Done" is not used for anything. Add another line at the bottom "Command = ''" lined up with the "elseif" to remove stale input. First it prints out the header stuff, then loops around asking for your input, then processing the input, then back to the loop start.

Related

KeyError when user input is misspelled

I have to program a text based game where conditions must be met before the game can end. As long as the user input is spelled correctly the game can be completed. However is there is a spelling error I get a KeyError: 'Whatever the misspelled word is'
I can't figure out how to resolve this issue. I have tried to check if user_input in rooms, I've tried to use try:/except:, I just can't figure it out. Would appreciate if someone could steer me in the right direction!
def main():
current_room = 'Mid Deck'
user_input = None
while user_input != 'Exit': #Check to see if user wants to exit game
print('You are in', current_room + '.' ) #Print list of possible user actions
options = rooms.get(current_room)
for i in options:
print(i, 'is', options[i])
user_input = input('What do you want to do?:').capitalize() #Get user input
if user_input == 'Exit':
print('Sorry you lost!')
elif user_input == 'Checklist': #Command to check which consoles have been activated
print('\n'.join(checklist))
elif user_input == 'Activate': #Command to activate consoles and update dictionary and list to reflect user input
if current_room == 'Bridge':
if win_condition < 7:
print('If you activate the console now')
print('the ships systems will short circuit')
print('and you will never escape the gravity well.')
print('Do you still want to activate? Yes or No?')
user_input = input().capitalize()
if user_input == 'Yes':
print('You have lost the game!')
else:
print('You have left the Bridge.')
current_room = 'Navigation'
else:
print('Congratulations you have escaped the stars gravity well!')
print('Thanks for playing and safe journey home!')
else:
checklist.append(current_room + ' is online.')
rooms[current_room]['Console'] = 'Online'
else:
current_room = rooms[current_room][user_input]
The KeyError is probably raised when the user input a not defined key in:
current_room = rooms[current_room][user_input]
To handle this issue you have to define which input is valid.
current_room_keys = ['Navigator', ...] #room key that valid
Some pseudo-code:
while user_input != 'Exit': #Check to see if user wants to exit game
user_input = input('What do you want to do?:').capitalize() #Get user input
if user_input == 'Exit':
elif user_input == 'Checklist': #Command to check which consoles have been activated
elif user_input == 'Activate': #Command to activate consoles and update dictionary and list to reflect user input
elif user_input in current_room_keys:
current_room = rooms[current_room][user_input]
else:
print('Please input a valid key')
continue

While loop not breaking?

I have written a main script that has a menu with 5 different options, the fifth option is if the user wants to quit the program. If the user types 5 in the main menu the program is supposed to quit, but it doesn't... It just keeps on looping through the menu. Can anyone help me resolve this issue??
menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
break
You have nested loops, and break only breaks out of the inner loop.
To remedy this delete the nested loop and the break from the else block:
while True:
choice = displayMenu(menuItems)
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
In your code, when you call break, it breaks from the inner while loop and goes to the outer while loop which causes the whole thing to go on again. If for some cases you want both of the while loops to break then you can use some sort of a flag.
Example,
flag = False
while True:
while True:
if (1 == var):
flag = True
break
if flag:
break
//Your code
flag = False
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
flag = True
break
elif (choice == 2):
checkErrors(grades)
flag = True
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
flag = True
break
else:
print("Invalid input, please try again")
flag = True
break
if True == flag:
break

How do I keep repeating "if"s?

I want my if function to keep repeating on python when it falls onto else. How do I do that? I've added an example of my code.
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...") quit()
else:
selection1 == print("The character you entered has not been recognised, please try again.")
I don't know whether you meant this but this program does exactly as what your question asks
while True:
selection1 = input("Enter Character\n")
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...")
break
else:
selection1 == print("The character you entered has not been recognised, please try again.")
The program takes in characters as inputs and checks them with the hardcoded characters. If not matched it will ask for the user to repeat until the letter Q is matched. An output can be
Enter Character
C
Ok
Enter Character
E
Ok
Enter Character
v
The character you entered has not been recognised, please try again.
Enter Character
Q
Ok...
Here are two possible approaches
while True: # i.e. loop until I tell you to break
selection1 = GetSelectionFromSomewhere()
if selection1 == 'C':
print('Okay...')
break
elif selection1 == 'E':
print('Okay...')
break
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
Some purists dislike while True loops because they don't make it explicit what the looping condition is at first glance. Here's another listing, which has the advantage of keeping break statements and other housekeeping out of your if cascade, so you can focus on the necessary actions there:
satisfied = False
while not satisfied:
selection1 = GetSelectionFromSomewhere()
satisfied = True
if selection1 == 'C':
print('Okay...')
elif selection1 == 'E':
print('Okay...')
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
satisfied = False
while selection1 != "Q":
if selection1 == "C":
print "Ok"
elif selection1 == "E":
print "Ok"
else:
print " Chose again"
print "quit"
quit()
while True:
n = raw_input("\nEnter charachter: ")
if n == "C" OR n=="E" OR n=="Q":
print("Ok !")
break # stops the loop
else:
n = "True"
characters = {'C','E','Q'}
def check():
ch=raw_input("type a letter: ")
if ch == q:
quit()
print "ok" if ch in characters else check()
check()
But you have already your answer from the previous posts. This is just an alternative.

Python Selecting menu choice

I'm new to python programming and I'm having trouble selecting an option. I have created a menu for example I have :
Instructions
Catering
Packages
add
When the user selects i, c, a or p each menu will come up. However, if the user selects 'p' before 'a' then I need to set a prompt to select a first..
INSTRUCTIONS = "I"
CATERING = "C"
PACKAGES = "P"
def menu():
userInput = True
while userInput != False:
print("Instructions
Catering
Packages")
userInput = input(">>>")
if userInput == INSTRUCTIONS:
instructions()
elif userInput == CATERING:
Catering()
elif userInput == PACKAGES:
Packages()
else:
print("Error")
Thank you
Here is the Code in a Loop::
def menu():
while True:
u_in=raw_input("Input Here:: ")
u=u_in.lower()
if u_in=="":
continue
elif u=="i":
Instructions()
elif u=="c":
Catering()
elif u=="p":
Packages()
If you are using python2.x, use raw_input() instead of input().
def menu():
mybool == True
userInput = input("Instructions\nCatering\nPackages\n>>> ")
b = userInput.lower()[0]
if b == 'a':
mybool = True
elif b == 'i':
Instructions()
elif b == 'c':
Catering()
elif b == 'p':
if mybool == True:
Packages()
else:
input('Here is where we display a prompt! ')
else:
print("Error")
Basically, this sets a variable to be False, and then gets input. If the input is a, then we set myBool to be True. If the user selects p and myBool is True (a has already been selected), it carries on. Otherwise, it displays a prompt.

How to break a loop when inputting unspecified raw_input?

I want to write an interface using a while loop and raw_input.
My code looks like this:
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit)
if n.strip() == 'p':
mp3.pause()
if n.strip() == 'u':
mp3.unpause()
if n.strip() == 'p':
mp3.play()
if n.strip() == 's':
mp3.stop()
if n.strip() == 'q':
break
But I want it to break if I input anything that isn't specified in the raw_input.
if not raw_input:
break
Returns and IndentationError: unindent does not match any outer indentation level.
if not raw_input:
break
Does not return any error but doesn't work as I want it to. As far as I know, it does nothing at all.
Also, if there's a cleaner way to write my loop, I love to hear it.
You are getting an indent error because you do not have a closing double quote.
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit")
If you want to have the while look break if there is any other value then put all of your conditions into elif statements, and an all includisve else at the end. Also I just put lower and strip onto the end of the raw_input statement.
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'pl' = play 's' = stop, 'q' = quit").strip().lower()
if n == 'p':
mp3.pause()
elif n == 'u':
mp3.unpause()
elif n == 'pl':
mp3.play()
elif n == 's':
mp3.stop()
elif n == 'q':
break
else:
break
You could also put all of the valid answer options into a dictionary, but it looks like you should start with the simple solution to understand the flow. Also you used a p for both play and pause. You will want to use a unique value to differentiate so I added 'pl' for play.
I think you can use a dict to hold all function is a cleaner way.
func_dict = {
'pause': mp3.pause,
'unpause': mp3.unpause,
'play': mp3.play,
'stop': mp3.stop,
}
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit")
if n.strip() in func_dict.keys():
func_dict[n]()
else:
break

Categories