定义一个函数,该函数将执行各种任务,但以某个inpu终止

2024-04-20 13:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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语句在pickone()函数中通过if语句后重新启动,但它只是显示终止并结束程序。你知道吗

因为有人说我的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函数有问题,它应该返回input not showtemption()


Tags: oftheto函数inreturnifnot
2条回答

我喜欢做这样的菜单

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)

为了获得一个将一直持续到终止的循环,您可以尝试以下操作:

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

为了弄清楚为什么选择了quit值后循环仍在继续,请尝试打印choice中的内容,也许它得到的是integer值而不是string?你知道吗

如果是这样,不妨试试:

choice = str(pickone())

或者

while str(choice) not in quitlist:
    ...

相关问题 更多 >