我试图让我的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次尝试,则退出程序。
答案 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()