将循环到循环设置为最多3次

时间:2016-02-24 20:01:01

标签: python function loops python-3.x while-loop

我试图让我的while循环在程序退出前最多循环3次,同时告知用户剩余的尝试。

def main():
    valid = 0
    while (valid == 0):
        valid = checkValid ()
    print ('and the program continues on with User_Input2()...')
    #User_Input2()

以下是checkValid()

的代码
def checkValid():
    if ((iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80)):
        result = 0
    else:
        result = 1
    return result

主程序是什么样的:

iVelocity = float(input('Please enter an initial velocity between 20 to 800 m/s: ' ))
iTrajectory = float(input('Please enter an initial trajectory angle between 5 to 80 degrees: '))

main()

我不确定在哪个函数中添加代码以使其循环(或者如果我需要创建def counter():行的内容),请告知用户剩余的尝试,以及如何如果已经使用了所有3次尝试,则退出程序。

2 个答案:

答案 0 :(得分:1)

尝试使用for循环break命令:

for i in range(3):
    valid =checkValid()
    if(valid==1):
        break

答案 1 :(得分:1)

我会在main中包含输入请求。根据我的理解,你想要这样的东西:

def main():
    valid = 0
    count = 1
    while (valid == 0):
        iVelocity = float(input('Please enter an initial velocity between 20 to 800 m/s: ' ))
        iTrajectory = float(input('Please enter an initial trajectory angle between 5 to 80 degrees: '))
        valid = checkValid(iVelocity, iTrajectory)
        if count == 3:
            break
    print ('and the program continues on with User_Input2()...')
    #User_Input2()

def checkValid(iVelocity, iTrajectory):
    if ((iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80)):
        result = 0
    else:
        result = 1
    return result

main()