Python文本菜单无限循环

时间:2013-05-30 15:00:30

标签: python

我在Python中创建一个简单的文本菜单,每次进入菜单的while循环时,它都会变成无限的......我不确定发生了什么,我觉得这应该可以正常工作。

 # Menu system!
def menu():
        print "blahblah options"

loop = 1
choice = 0
while loop == 1:
    choice = menu()
    if choice == 1:
        add(input("Add this: "),input("to this: "))
    elif choice == 2:
        sub(input("Subtract this: "),input("from this: "))
    elif choice == 3:
        mul(input("Multiply this: "),input("by this: "))
    elif choice == 4:
        div(input("Divide this: "),input("by this: "))
    elif choice == 5:
        loop = 0

这里发生了什么导致它无休止地遍历顶部的print语句?

3 个答案:

答案 0 :(得分:5)

您在menu中遗漏了一行,或者在其他地方错过了input。您实际上还没有接受用户的选择。如果您想保留当前结构,menu应如下所示:

def menu():
    print 'options...'
    return int(raw_input())

或者,更清洁一点(效果相同):

def menu():
    return int(raw_input('options...'))

否则,您只需拨打menu(),然后分别接受用户的选择:

while loop == 1:
    menu()
    choice = int(raw_input())

注意我已将input()来电更改为int(raw_input())。这是一种很多更安全的方式来接受用户的输入,因为它阻止他们在输入中嵌入任意Python代码!


不会-相当-ON-主题:

现在,只是因为我碰巧注意到它,我还要提到loop是一个潜在误导性的变量名。由于您只是将它用作布尔值,您可以像这样重写while循环:

loop = 1
while loop: # !
    #do stuff

这很有趣,但读起来不是很直观。简单地无限循环通常更好,并在满足最终条件时使用break

while True:
    # Do stuff
    if choice == 5: #Or whatever end condition
        break

答案 1 :(得分:1)

menu是一个打印内容并返回None的函数。执行choice=menu()时,选项设置为None。没有你的if匹配和循环无休止地重复。

更好的选择是提示用户输入menu()并返回用户输入。请记住首先将用户输入转换为int(因为您将选项与整数进行比较)

choice = int(raw_input("Enter your choice:"))
return choice

答案 2 :(得分:0)

而不是在menu内打印选项,你应该返回它们,因为choice需要menu()的返回值,并且menu没有返回任何内容,所以默认返回值None被赋值每次choice

def menu():
        return "blahblah options"

loop = 1
choice = 0
while loop == 1:
    choice = menu()
    if choice == 1:     #this is always None
        add(input("Add this: "),input("to this: "))
    elif choice == 2:
        sub(input("Subtract this: "),input("from this: "))
    elif choice == 3:
        mul(input("Multiply this: "),input("by this: "))
    elif choice == 4:
        div(input("Divide this: "),input("by this: "))
    elif choice == 5:
        loop = 0

您应该从用户那里获取输入,而不是从菜单返回固定值:

def menu():
        strs = ('Enter 1 for addition\n'
                'Enter 2 for subtaction\n'
                'Enter 3 for multiplication\n'
                'Enter 4 for division\n'
                'Enter 5 to exit : ')
        choice = raw_input(strs)
        return int(choice) 

while True:          #use while True
    choice = menu()
    if choice == 1:
        add(input("Add this: "),input("to this: "))
    elif choice == 2:
        sub(input("Subtract this: "),input("from this: "))
    elif choice == 3:
        mul(input("Multiply this: "),input("by this: "))
    elif choice == 4:
        div(input("Divide this: "),input("by this: "))
    elif choice == 5:
        break