当满足条件时,循环无法终止

时间:2016-11-15 12:15:35

标签: python loops

为什么在满足所需条件时循环无法终止。 我希望得到一个深入的解释,而不是为我纠正的代码。

def get_name(name_type):
    return raw_input("Please enter you're {}name: \n".format(name_type)) 
def UserName():
    result = get_name("Fore"), get_name("Middle"), get_name("Sur")
    return " ".join(result)

print("You're UserName is : " + UserName())

while True:
    def Base():
        return int(raw_input("Please select a base number: \n"))
    def Power():
        return int(raw_input("Please select a power number: \n"))
    def result():
        return Base()*Power()

    print result()

    cont = raw_input("Would you like to quit? yes/no > ")
    while cont.lower() not in ("yes","no"):
          cont = raw_input("Would you like to quit? yes/no > ")
          if cont=="no":
              break

3 个答案:

答案 0 :(得分:2)

您的break语句嵌套在内部while循环中,因此它打破了循环而不是while True循环。我认为将条件语句移出内部循环并将逻辑更改为if discont=='yes'(注意:将var重命名为更准确的描述)将为您提供所需内容:

while True:

    ...

    discont = raw_input("Would you like to quit? yes/no > ").lower()
    while discont not in ("yes","no"):
        discont = raw_input("Would you like to quit? yes/no > ").lower()
    if discont=="yes":
        break

答案 1 :(得分:1)

现在确实如此:

def get_name(name_type):
    return raw_input("Please enter you're {}name: \n".format(name_type)) 
def UserName():
    result = get_name("Fore"), get_name("Middle"), get_name("Sur")
    return " ".join(result)

print("You're UserName is : " + UserName())
print

cont = 'no'

while cont != 'yes':
    def Base():
        return int(raw_input("Please select a base number: \n"))
    def Power():
        return int(raw_input("Please select a power number: \n"))
    def result():
        return Base()*Power()

    print result()

    cont = raw_input("Would you like to quit? yes/no > ")
    while cont.lower() not in ("yes","no"):
          cont = raw_input("Would you like to quit? yes/no > ")
          if cont=="yes":
              break

答案 2 :(得分:0)

你在两个循环中。 如果用户想要退出,你想要突破两者,否则只会退出内部:将条件移出while循环,然后它应该工作:

from sys import exit

...

while True:
    def Base():
        return int(raw_input("Please select a base number: \n"))
    def Power():
        return int(raw_input("Please select a power number: \n"))
    def result():
        return Base()*Power()

    print result()

    cont = raw_input("Would you like to quit? yes/no > ")
    while cont.lower() not in ("yes","no"):
        cont = raw_input("Would you like to quit? yes/no > ")
    if cont=="yes":
        break

下一条建议与您的问题无关,但无论如何我都会给出:没有必要定义BasePower和{ {1}}在每次循环迭代中起作用。只需将值分配给变量并直接打印:

Result