def main():
choice = pickone() #picking the shape or to quit
if choice not in quitlist:
low, high = getLoHiInt() #picking the range of points
shapes = [ball,bowlingPin,ellipse,tableLeg]
combolist = zip(picklist,shapes) #zipped list of the shapes with the corresponding choice
analyzeSolid(combolist[int(choice)-1][1], low, high)
return showTermination()
pickone()函数工作得很好,问题是当我输入终止数时,我的函数显示终止但是继续通过if循环,即使选择在quitlist中。
quitlist = ['5']
不幸的是我需要这种方式,因为我的代码的其他部分依赖于此。我还需要我的if语句在它通过if语句后在pickone()函数重新启动,但它只是显示我的终止而是结束程序。
因为有人说我的pickone功能不能正常工作
picklist = ["1","2","3","4"]
quitlist = ["5"] #couldn't get it to work with just one list, but this works fine
def pickone():
while True:
print "\nPick a solid to analyze: \n1: ball\n2: bowlingPin\n3: ellipse\n4: tableleg\n5: quit"
theinput = raw_input("What is the number of your choice?: ")
#if theinput not in zip(picklist, quitlist):
# print"\nChoice %s is not a valid choice.\n" %theinput
try:
theinput
except ValueError:
# So the program will continue if the input is wrong
print "choice must be from 1 to 5" #message doesn't show up but the program still works properly
continue
if theinput in picklist:
return theinput
if theinput in quitlist:
return theinput
编辑,我的pickone函数出现问题,它应该返回输入而不是showTermination()
答案 0 :(得分:1)
为了获得一个可以持续到终止的循环,你可以尝试类似的东西:
def main():
choice = pickone() #picking the shape or to quit
while choice not in quitlist:
low, high = getLoHiInt() #picking the range of points
shapes = [ball,bowlingPin,ellipse,tableLeg]
combolist = zip(picklist,shapes) #zipped list of the shapes with the corresponding choice
analyzeSolid(combolist[int(choice)-1][1], low, high)
choice = pickone()
return showTermination()
为了弄清楚为什么你的循环在继续选择退出值时,请尝试打印出choice
中的内容,也许它会获得integer
值,而不是string
}?
如果是这种情况,可以尝试:
choice = str(pickone())
或
while str(choice) not in quitlist:
...
答案 1 :(得分:1)
我喜欢制作这样的菜单
def do_menu(menu,error="Invalid Choice Try Again!"):
while True:
for k,(msg,action) in menu.items():
print msg
resp = raw_input("Make a Choice:")
if resp in menu:
return menu[resp][1]()
print error
import random,sys
#####JUST SOME GENERIC MENU ACTIONS
something = []
def add_something():
something.append(random.randint(1,10))
print "ADDED %d"%something[-1]
def print_something():
print something
#DEFINE THE MENU
menu = {
'A':("[A]dd Something",add_something),
'P':("[P]rint Something",print_something),
'Q':("[Q]uit",sys.exit)
}
while True:
#print menu and get user response and act upon it
print "\n#####[ MENU ]####"
result = do_menu(menu)