"while loop"不中断(使用Python)



这是我的代码:

#Choose Report
def chooseReport():
    print "Choose a report."
    while True:
        choice = raw_input("Enter A or B: ")
        if choice == 'a' or choice == 'A':
            reportA()
            break
        elif choice == 'b' or choice == 'B':
            reportB()
            break
        else:
            continue

当我输入ab时,它只是要求我再次"Enter A or B"。它不会转到它应该去的功能。

知道这是为什么吗?

代码是完美的,除了多余的其他,如注释中所述。您是否输入a(a + 空格(而不是简单的a(没有空格(?问题出在您提供的输入中,而不是在代码中!

def chooseReport():
    print "Choose a report."
    t=True                                        # t starts at true
    while t:
        choice = raw_input("Enter A or B: ")
        if choice == 'a' or choice == 'A':
            reportA()
            t=False               # t turns false to break out of loop
        elif choice == 'b' or choice == 'B':
            reportB()
            t=False

试试这个。当 t 为真时,它保持循环,当 t 为假时停止。问题也可能出在报告 A 或报告 B 中,或者您如何调用 chooseReport。

问题出在raw_input() .它返回一个字符串,但也许这个字符串是"a ""an",尽管你输入了"a""b"

我会这样做:

def chooseReport():
    print "Choose a report."
    while True:
        choice = raw_input("Enter A or B: ")
        if "a" in choice or "A" in choice:
            reportA()
            break
        elif "b" in choice or "B" in choice: 
            reportB()
            break
        else:
            continue

在以下脚本中尝试了您的代码,它在Linux和Windows上都可以正常工作。

def reportA():
    print "AAAAA"
def reportB():
    print "BBBBB"
#Choose Report
def chooseReport():
    print "Choose a report."
    while True:
        choice = raw_input("Enter A or B: ")
        if choice == 'a' or choice == 'A':
            reportA()
            break
        elif choice == 'b' or choice == 'B':
            reportB()
            break
        else:
            continue

chooseReport();

首先,你的代码工作正常,最有可能的错误是你写了一个错误的输入(例如:有更多的字符(。要解决这个问题,您可以使用 "a" in choice or "A" in choice .但如果它不起作用...继续阅读。

似乎break不影响while loop,我没有python 2,所以我不太确定为什么(在python 3中[更改为raw_input input后,print更改为print()]您的代码工作完美(。所以你应该用while的条件来打破它。

while True理论上永远有效,因为每次执行代码时,它都会检查条件 - True - 并且因为它是真的,所以它不断循环。
您可以操纵该条件以中断循环(不允许再次执行其代码(。

例如,您可以使用以下内容:

#Choose Report
def chooseReport():
    print "Choose a report."
    allow = True    # allow start as True so the while will work
    while allow:
        choice = raw_input("Enter A or B: ")
        if choice.lower().strip() == "a":    # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
            reportA()
            allow = False   # allow now is False, the while won't execute again
        elif choice.lower().strip() == "b":
            reportB()
            allow = False   # allow now is False, the while won't execute again
        # The else is complete redundant, you don't need it

代码很好。我认为您在循环中调用 chooseReport(( 函数,或者您的输入有额外的字符,并且条件不满足。