'While loop with if/else statement in Python

So I am still in the process of learning Python and I am having difficultly with while loops. I have a sample of code below that includes while loop and if and else statements. What I want it to do is print 'Less than 2' and 'Greater than 4' which it does, but it keeps running. It does not print it just once each which is what I would want it to do. Any help would be greatly appreciated!

counter = 1
while (counter < 5):
    count = counter
    if count < 2:
        counter = counter + 1
    else:
        print('Less than 2')
    if count > 4:
        counter = counter + 1
    else:
        print('Greater than 4')
    counter = counter + 1 


Solution 1:[1]

I'm assuming you want to say Less than 2 or Greater than 4 while incrementing from 1 to 4:

counter = 1
while (counter < 5):
    if counter < 2:
        print('Less than 2')
    elif counter > 4:
        print('Greater than 4')
    else:
        print('Something else') # You can use 'pass' if you don't want to print anything here
    counter += 1

The program will never display Greater than 4 because your while condition is counter < 5.

Solution 2:[2]

  1. Declare a variable called username1 and assign a value to it
  2. Declare a variable called password1 and assign a value to it
  3. Declare a variable called isCorrect and assign to it the boolean value True
  4. Create a program that asks the user to enter his username (variable name: username2) and password (variable name: password2) and save them
  5. The program will check if the entered username (username2) and password(password2) are the same defined in username1 and password1
  6. if Yes print HAPPY LOGIN
  7. if not ask again the user to enter new values and check again

Solution 3:[3]

What a while-loop says is if True, keep doing till False. If you watch automate the boring stuff- While Loops on YouTube it should give you a understanding of how a while loop can be used and why a if-statement can be best in other cases..

password = ''

while password != 'your password':
    password = input('Please enter your password... ')
print('Thank you')
  1. Variable password is set as a blank string

  2. password is not an input equal to string "your password", which makes the while expression True, while true repeat. if password does equal 'your password' expression is false, exit loop.

  3. While password equals anything except 'your password', expression is True, repeat loop till False.

  4. If loop becomes False, print end of line, 'Thank you', end program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Scratch'N'Purr
Solution 2 Rimkhaled
Solution 3 AspiringLu