MikeD
MikeD

Reputation: 55

Setting While Loop to Loop Maximum of 3 Times

I'm trying to get my while loop to loop a maximum of 3 times before the program quits while also informing the user of their remaining attempts.

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

And here is the code for checkValid()

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

And what the main program looks like:

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()

I'm not sure where to add code in either function to get it to loop (or if I need to create something along the lines of def counter():), inform the user of their remaining attempts, and how to quit the program if all 3 attempts have been used.

Upvotes: 1

Views: 3350

Answers (2)

Mantxu
Mantxu

Reputation: 319

I would include the input request in main. On my understanding, you want something like this:

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()

Upvotes: 1

Destruktor
Destruktor

Reputation: 463

Try using a for loop with break command:

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

Upvotes: 3

Related Questions