【问题标题】:What is the proper way to use continue?使用 continue 的正确方法是什么?
【发布时间】:2023-11-29 05:54:01
【问题描述】:

在使用 continue 后,我在完成另一次迭代时遇到了问题。目标是获得大于或等于 3 的整数输入。我不希望脚本在用户身上出错,而​​是我想要求另一个输入。

while True:
    try:
        sides = int(raw_input("Marty wants to draw you a shape. How many sides will the shape have?"))
    except ValueError:
        print "Marty needs an integer, try again."
        continue
    if sides < 2:
        print "Marty needs a number greater than 2, try again."
        continue
    else:
        break

使用 continue 两次时是否会出现问题?任何关于正确使用 continue 的建议都会很棒。就目前而言,它要求用户输入。如果给出的不是整数,它会要求另一个输入。如果给定 2,它什么都不做,甚至不打印,更不用说再次尝试输入了。

【问题讨论】:

    标签: python-2.7 exception syntax break continue


    【解决方案1】:

    问题不在于您对 continue 的使用,而在于您对输入的评估。而不是你所拥有的,尝试:

    if sides <= 2:
        print 'Marty needs a number greater than 2, try again.'
        continue
    

    或:

    if sides < 3:
    

    【讨论】:

    • 谢谢你的工作!很高兴知道这不是一个持续的问题。
    最近更新 更多