Menu and submenu python - python

How can I return from a sub menu to a main menu?
Also I want to keep the data generated in the submenu.
Main menu:
1. Load data
2. Filter data
3. Display statistics
4. Generate plots
5. Quit
On option 2 I have a submenu:
1. S. enterica
2. B. cereus
3. Listeria
4. B. thermosphacta
5. Quit
def mainMenu():
menuItems = np.array(["Load data", "Filter data", "Display statistics", "Generate plots", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria", "B. thermosphacta", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
data = data[data[:,2] == 1] # 1 - S. enterica
elif choice == 2:
data = data[data[:,2] == 2] # 2 - B. cereus
elif choice == 3:
data = data[data[:,2] == 3] # 3 - Listeria
elif choice == 4:
data = data[data[:,2] == 4] # 4 - B. thermosphacta
elif choice == 5:
return data
continue
if choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break

I implemented the break statement in the submenu and placed the menuItems inside the loops. This worked and data created in the submenu (subchoice) can be used in the mainMenu options 3 & 4.
import numpy as np
from displayMenu import *
from dataLoad import *
from dataStatistics import *
from dataPlot import *
from bFilter import *
def mainMenu():
while True:
menuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta", "Back to main menu"])
subchoice = displayMenu(menuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
if subchoice == 5:
break
continue
elif choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break

Replace your code with this:
def mainMenu():
mainMenuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
subMenuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta"])
while True:
choice = displayMenu(mainMenuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
subchoice = displayMenu(subMenuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
break
# The answer is not a correct one
continue
elif choice == 3: # instead of if
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
You donĀ“t need a "Quit" option in your submenu - you want to repeat the nested loop (the submenu) only in the case of wrong answer (other as 1, 2, 3 or 4).
No action is needed to save the contents of your data variable as all action you perform are inside of your mainMenu() function. But if you need it outside of your function, use the return data statement as the very last in your function, outside of any loop.

Related

UnboundLocalError while accessing option 2 in a choice menu

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.

Expected indented blockPylance

from tkinter import CENTER
global f
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,movie 1 ")
print("2,movie 2 ")
print("3,movie 3")
print("4,back")
movie = int(input("choose your movie: "))
if movie == 4:
# in this it goes to center function and from center it goes to movie function and it
comes back here and then go to theater
CENTER()
theater()
return 0
if f == 1:
theater()
# this theater function used to select screen
def theater():
print("which screen do you want to watch movie: ")
print("1,SCREEN 1")
print("2,SCREEN 2")
print("3,SCREEN 3")
a = int(input("choose your screen: "))
ticket = int(input("number of ticket do you want?: "))
timing(a)
# this timing function used to select timing for movie
def timing(a):
time1 = {
"1": "10.00-1.00",
"2": "1.10-4.10",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time2 = {
"1": "10.15-1.15",
"2": "1.25-4.25",
"3": "4.35-7.35",
"4": "7.45-10.45"
}
time3 = {
"1": "10.30-1.30",
"2": "1.40-4.40",
"3": "4.50-7.50",
"4": "8.00-10.45"
}
if a == 1:
print("choose your time:")
print(time1)
t = input("select your time:")
x = time1[t]
print("successful!, enjoy movie at "+x)
elif a == 2:
print("choose your time:")
print(time2)
t = input("select your time:")
x = time2[t]
print("successful!, enjoy movie at "+x)
elif a == 3:
print("choose your time:")
print(time3)
t = input("select your time:")
x = time3[t]
print("successful!, enjoy movie at "+x)
return 0
def movie(theater):
if theater == 1:
t_movie()
elif theater == 2:
t_movie()
elif theater == 3:
t_movie()
elif theater == 4:
city()
else:
print("wrong choice")
def center():
print("which theater do you wish to see movie? ")
print("1,Inox")
print("2,Icon")
print("3,pvp")
print("4,back")
a = int(input("choose your option: "))
movie(a)
return 0
# this function is used to select city
def city():
print("Hi welcome to movie ticket booking: ")
print("where you want to watch movie?:")
print("1,city 1")
print("2,city 2 ")
print("3,city 3 ")
place = int(input("choose your option: "))
if place == 1:
center()
elif place == 2:
center()
elif place == 3:
center()
else:
print("wrong choice")
city() # it calls the function city
Here is your code with the indentation fixed. At least, I think it's fixed, Your structure is confusing, so it's hard to tell.
from tkinter import CENTER
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,movie 1 ")
print("2,movie 2 ")
print("3,movie 3")
print("4,back")
movie = int(input("choose your movie: "))
if movie == 4:
# in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater
CENTER()
theater()
return 0
if f == 1:
theater()
# this theater function used to select screen
def theater():
print("which screen do you want to watch movie: ")
print("1,SCREEN 1")
print("2,SCREEN 2")
print("3,SCREEN 3")
a = int(input("choose your screen: "))
ticket = int(input("number of ticket do you want?: "))
timing(a)
# this timing function used to select timing for movie
def timing(a):
time1 = {
"1": "10.00-1.00",
"2": "1.10-4.10",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time2 = {
"1": "10.15-1.15",
"2": "1.25-4.25",
"3": "4.35-7.35",
"4": "7.45-10.45"
}
time3 = {
"1": "10.30-1.30",
"2": "1.40-4.40",
"3": "4.50-7.50",
"4": "8.00-10.45"
}
if a == 1:
print("choose your time:")
print(time1)
t = input("select your time:")
x = time1[t]
print("successful!, enjoy movie at "+x)
elif a == 2:
print("choose your time:")
print(time2)
t = input("select your time:")
x = time2[t]
print("successful!, enjoy movie at "+x)
elif a == 3:
print("choose your time:")
print(time3)
t = input("select your time:")
x = time3[t]
print("successful!, enjoy movie at "+x)
return 0
def movie(theater):
if theater == 1:
t_movie()
elif theater == 2:
t_movie()
elif theater == 3:
t_movie()
elif theater == 4:
city()
else:
print("wrong choice")
def center():
print("which theater do you wish to see movie? ")
print("1,Inox")
print("2,Icon")
print("3,pvp")
print("4,back")
a = int(input("choose your option: "))
movie(a)
return 0
# this function is used to select city
def city():
print("Hi welcome to movie ticket booking: ")
print("where you want to watch movie?:")
print("1,city 1")
print("2,city 2 ")
print("3,city 3 ")
place = int(input("choose your option: "))
if place == 1:
center()
elif place == 2:
center()
elif place == 3:
center()
else:
print("wrong choice")
city() # it calls the function city

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 to sucsessfully ask the user to choose between two options

New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])

Python Raspberry PI Guessing Game(Function call not working)

My problem is that my Random function doesn't get called from the Menu function. I've tried everything, but it still doesn't work. It's weird, because i think that i have structured the functions correctly, and everything should work fine, but it doesn't call Random.
def Menu():
name = raw_input("What's your name?\n:")
print "Hello, %s!\nWeclome to the Guessing Game!" % name
print "Select an option:"
print "1- Guess a number between 1-100."
print "2- Guess a number between 1-1000."
print "3- Guess a number between 1-10,000."
print "4- Guess a number between 1-100,000."
print "5- Exit."
try:
selection = raw_input("Enter your selection:")
if selection == 1:
Random(100)
elif selection == 2:
Random(1000)
elif selection == 3:
Random(10000)
elif selection == 4:
Random(100000)
elif selection == 5:
exit()
except:
os.system("clear")
print "Sorry, that wasn't an option. Enter your selection again."
Menu()
raw_input() retuns a string so you have to cast the input to int or compare the input with strings. Either this way:
selection = raw_input("Enter your selection:")
if selection == "1":
Random(100)
elif selection == "2":
Random(1000)
elif selection == "3":
Random(10000)
elif selection == "4":
Random(100000)
elif selection == "5":
exit()
or this way:
selection = raw_input("Enter your selection:")
if int(selection) == 1:
Random(100)
elif int(selection) == 2:
Random(1000)
elif int(selection) == 3:
Random(10000)
elif int(selection) == 4:
Random(100000)
elif int(selection) == 5:
exit()
Furthermore you can avoid try by kicking out elif int(selection) == 5: and using else:" instead. So the game will be ended with any other input than 1,2,3 or 4. There will be no possibility to "enter your selection again" after calling except in your code anyway because the script stops.
The function Random is not very optimal. See this:
def Random(select):
range = "1-" + str(select)
Correct_Guess = random.randint(1,select+1)
Difficulty()
It is the same but shorte and more readable ;)

Categories