Tag: python loop

  • Python – While Loop Examples

    Example 1 : Counting from 1 to 5

    count = 1
    
    while count <= 5:
        print(count)
        count = count+1

    Output :

    1
    2
    3
    4
    5

    Example 2 : Sum of Numbers from 1 to 10

    
    
    count = 1
    total_sum = 0

    while count <= 10:
    total_sum = total_sum + count
    count =count + 1

    print("The sum of numbers from 1 to 10 is:", total_sum)

    Output :

    The sum of numbers from 1 to 10 is: 55

    Example 3: Asking for a Password

    correct_password = "root1234"
    
    while True:
        password = input("Enter the password: ")
        if password == correct_password:
            print("Access granted!")
            break                                          
        else:
            print("Incorrect password, try again.")

    Output :

    Enter the password: abc
    Incorrect password, try again.
    
    Enter the password: root1234
    Access granted!

    Example 4: To Print Even Numbers Between 1 and 10

    number = 2
    
    while number <= 10:
        print(number)
        number = number + 2

    Output :

    2
    4
    6
    8
    10

    Example 5: ATM Withdrawal

    balance = 1000
    
    
    while True:
        withdrawal = int(input("Enter amount to withdraw: "))
        
        if withdrawal > balance:
            print("Insufficient funds. Your balance is:", balance)
        else:
            balance -= withdrawal
            print("Withdrawal successful. New balance is:", balance)
            break 

    Output :

    Enter amount to withdraw: 1500
    Insufficient funds. Your balance is: 1000
    Enter amount to withdraw: 500
    Withdrawal successful. New balance is: 500

    Example 6: Password Retry Limits

    correct_password = "securePass"
    attempts_left = 3
    
    
    while attempts_left > 0:
        password = input("Enter the password: ")
        
        if password == correct_password:
            print("Access granted!")
            break 
        else:
            attempts_left -= 1
            print("Incorrect password. Attempts left:", attempts_left)
    
    if attempts_left == 0:
        print("Too many failed attempts. Access denied.")

    Output :

    Enter the password: wrong1
    Incorrect password. Attempts left: 2
    Enter the password: wrong2
    Incorrect password. Attempts left: 1
    Enter the password: securePass
    Access granted!