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.
Related
I have simplified it to this:
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
def two_player_word():
print("2")
elif gameinput == "1":
def one_player_word():
print("1")
def hangman():
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman()
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
I had previously defined gameinput in the 'hang()' it collects the user input and so on.
My problem is in the 'hangman()' I need gameinput again to make the variable word (its made so a user can either make a word (two_player_word) or one player when it generates a random word (one_player_word()
It works perfectly without gameinput being in a function but after the player either wins or loses I want it to let the user decide if they want to change gamemode or not as shown in main().
There is a lot more code but figured it would be easier to try figure out the problem using just this.
Just pass the gameinput from hang into hangman as an argument.
def hang():
while True:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput not in ("1", "2"):
continue
hangman(gameinput)
break
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
There are two problems that cause your code to fail (besides indentation).
You are defining nested functions (one/two_player_word) which you then try to call from outside the function (where they are not defined). You can change this by defining the functions outside the function hang().
hangman() uses the gameinput variable but it's not defined nor provided. You can change this by adding it as a parameter to the function call.
Your adjusted code could work like this:
import time
def one_player_word():
print("1")
def two_player_word():
print("2")
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
two_player_word()
elif gameinput == "1":
one_player_word()
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman(gameoverinput)
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
I have been trying different code combinations for three days now and I figured before i throw in the towel this might be a good place to ask my question. In my code, no matter how I try to declare the lists I've been unsuccessful. My problem currently is:
line 54, in main
inputExpenseAmounts(expenseItems)
UnboundLocalError: local variable 'expenseItems' referenced before assignment
import matplotlib.pyplot as plt
from prettytable import PrettyTable
def menu():
print('[1] Enter Expense Name')
print('[2] Enter Expense Amount')
print('[3] Display Expense Report')
print('[4] Quit')
choice = input('Enter choice: ')
return choice
def inputExpenseNames():
expenseItems = []
name = input("Enter expense name (q for quit) \n")
while name != "q" :
expenseItems.append(name)
name = input("Enter expense name (q for quit) \n")
return expenseItems
def inputExpenseAmounts(expenseItems):
expenseAmounts = []
print("Enter the amount for each expense ")
for i in expenseItems:
amount = int(input(i + " : "))
expenseAmounts.append(amount)
return ExpenseAmounts
def displayExpenseReport(expenseItems, expenseAmounts):
displayExpenseReport = []
option = input("Display in \n (a) table \n (b) bar chart \n (c) pie chart \n")
if option == "c":
plt.pie(expenseAmounts, labels = expenseItems)
plt.show()
elif option == "b":
plt.bar(expenseItems, expenseAmounts)
plt.show()
elif option == "a":
t = PrettyTable()
t.add_column("expenseItems",expenseItems)
t.add_column("expenseAmounts",expenseAmounts)
print(t)
else:
print("Invalid option - allowed only (a / b / c")
def main():
while True:
choice = menu()
if choice == '1':
inputExpenseNames()
elif choice == '2':
inputExpenseAmounts(expenseItems)
elif choice == '3':
displayExpenseReport(expenseItems, expenseAmounts)
elif choice == '4':
break
else:
print('Invalid selection. Please re-enter.')
expenseItems = inputExpenseNames()
main()
The error is telling you that you used a variable (expenseItems) that hadn't been defined yet.
What you probably want to do is initialize those variables to empty lists, and then store the results of calling your earlier menu functions so you can pass them to the later functions.
def main():
expenseItems = []
expenseAmounts = []
while True:
choice = menu()
if choice == '1':
expenseItems = inputExpenseNames()
elif choice == '2':
expenseAmounts = inputExpenseAmounts(expenseItems)
elif choice == '3':
displayExpenseReport(expenseItems, expenseAmounts)
elif choice == '4':
break
else:
print('Invalid selection. Please re-enter.')
I'll note that you may want to rethink the idea of having a menu here, since the user always must go through the items in the exact order they're listed. It would be simpler to just automatically go through the three steps in order.
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
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.
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.