How do I use a while loop in python?



  • Also see: python help - while statement.

    Demo code.

    counter = 1
    while counter <= 5:
        print(counter)
        counter = counter + 1
    print("I can count")```
    

    The result is.

    $ python main.py
    1
    2
    3
    4
    5
    I can count
    

    Here's a lot more useful while code example. Note that the correct_value would normally be extracted from a database of some type and not hard coded.

    The demo code combines the while loop with if conditions.

    correct_value = 3471
    attempts = 0
    max_attempts = 3
    
    while attempts < max_attempts:
        passcode = int(input('Enter the correct value to proceed:'))
        attempts += 1
        attempts_left = max_attempts - attempts
        if passcode == correct_value:
            print("Great, Access Permitted!")
            break
        else: 
            print(f"Please try again, you have {attempts_left} attempts left")
    else:
        print(f"Maximum attempts exceeded.")
    

    Example execution of the code.

    $ python main.py
    Enter the correct value to proceed:
    2345
    Please try again, you have 2 attempts left
    Enter the correct value to proceed:
    6554
    Please try again, you have 1 attempts left
    Enter the correct value to proceed:
    3471
    Great, Access Permitted!
    

    If the correct value was not entered. The else statement will be displayed:

    $ python main.py
    Enter the correct value to proceed:
    5678
    Please try again, you have 2 attempts left
    Enter the correct value to proceed:
    1234
    Please try again, you have 1 attempts left
    Enter the correct value to proceed:
    6345
    Please try again, you have 0 attempts left
    Maximum attempts exceeded.
    

Log in to reply
 

© Lightnetics 2024