繁体   English   中英

退出while循环的中间,无需重复代码

[英]Break out of the middle of a while loop, without repeating code

我问用户一系列问题并记录他们的答案。 我的提问者检查这些答案的格式,如果用户输入了奇怪的内容(例如my name is 102 ),则返回一个标志。

如果这些答案有任何错误,我希望该程序立即脱离问题集。 我正在尝试使用while循环来执行此操作,但对我来说很明显,这个while循环仅在每个循环结束时检查标志的值,因此直到问题已经解决。

注意,在此示例中,“ letter”变量是用户输入的替代。 这不是代码的实际外观。

def string_checker(letter, output):
    if type(letter) != str:
        print('You did not give me a string!')
        output = 1

    return output

output = 0
# this should go until question 3, when the user makes a mistake
while output == 0:

    # question 1
    letter = 'bob'
    print(letter)
    output = string_checker(letter, output)

    # question 2
    letter = 'aldo'
    print(letter)
    output = string_checker(letter, output)

    # question 3 --- user gets this wrong
    letter = 1
    print(letter)
    output = string_checker(letter, output)

    # question 4
    letter = 'angry'
    print(letter)
    output = string_checker(letter, output)

# but it seems to ask question 4, regardless
print('done!')

我有办法修改此代码,以便从不问question 4吗?

基于贾斯珀答案的更新代码

以Jasper的答案为基础并提供完整的解决方案...对我的问题的此修改解决了它。 通过在检查功能内部引发ValueError,try块立即失败,我们可以使用return从main逃脱。

def string_checker(letter):
    if type(letter) != str:
        raise ValueError

def main():
    # this should go until question 3, when the user makes a mistake
    try:

        # question 1
        letter = 'bob'
        print(letter)
        string_checker(letter)

        # question 2
        letter = 'aldo'
        print(letter)
        string_checker(letter)

        # question 3 --- user gets this wrong
        letter = 1
        print(letter)
        string_checker(letter)

        # question 4
        letter = 'angry'
        print(letter)
        string_checker(letter)

    # we make a mistake at question 3 and go straight to here
    except ValueError as ve:
        print('You did not give me a string!')
        return 'oops'

    # exit
    return 'done'

您可以在每个问题之后检查string_checker的结果是否为1

if output == 1:
    break

break语句将立即退出循环。

这样,您就不需要在while拥有该条件,因此您可以无限期地while

while True:
    ...
# question 3 --- user gets this wrong
letter = 1
print(letter)
output = string_checker(letter, output)

# Add this to your code:

if output == 1:
    break

中断完全从while循环中跳出,您很好。 唯一的问题是,计算机仍会

print('done!')

因此,也许您想包含错误代码或类似内容。

也许像?

if output == 1:
    print "You have given an invalid input"
    break

编辑:

我意识到它会打印“您提供了无效的输入”,然后打印“完成!”。

因此,您应该让程序停止使用无效输入运行:

if output == 1:
    print "You have given an invalid input"
    return

return语句将完全停止程序。

虽然这不能回答问题标题,但我认为循环是错误的设计选择(假设您不会多次提出相同的问题)。 相反,您可以引发异常:

try:
  # ask question

  if not string_checker(...):
    raise ValueError

  # ask next question

except ValueError as ve:
  print("wrong answer")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM