If statement in while loop 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 

asked Apr 25, 2016 at 14:12

A.LeBrunA.LeBrun

1511 gold badge1 silver badge11 bronze badges

3

counter = 1 
while (counter <= 5): 
    if counter < 2:
        print("Less than 2")
    elif counter > 4:
        print("Greater than 4")
    counter += 1

This will do what you want (if less than 2, print this etc.)

answered Apr 25, 2016 at 14:24

trolley813trolley813

7997 silver badges15 bronze badges

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.

answered Apr 25, 2016 at 14:22

If statement in while loop python

Scratch'N'PurrScratch'N'Purr

9,0912 gold badges31 silver badges47 bronze badges

  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

answered Nov 19, 2020 at 14:04

1

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.

answered May 16 at 3:40

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.

Video: Python while Loop

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:
    Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Flowchart of while Loop

If statement in while loop python
Flowchart for while loop in Python

Example: Python while Loop

# Program to add natural
# numbers up to 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).

We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).

Finally, the result is displayed.


While loop with else

Same as with for loops, while loops can also have an optional else block.

The else part is executed if the condition in the while loop evaluates to False.

The while loop can be terminated with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.

'''Example to illustrate
the use of else statement
with the while loop'''

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the fourth iteration, the condition in while becomes False. Hence, the else part is executed.

Table of Contents

  • What is while loop in Python?
    • Syntax of while Loop in Python
    • Flowchart of while loop
    • Example: Python while Loop
  • While loop with else

Can I put an if statement in a while loop Python?

Python while loop boolean condition To check the boolean expression in while loop condition we can simply use while if condition. It checks if the 'a' variable is true and the loop will exit after 3 iteration values (n=n+1) must be terminated 3 times until n==4.

Can we use if and while loop in Python?

if password does equal 'your password' expression is false, exit loop. While password equals anything except 'your password', expression is True, repeat loop till False. If loop becomes False, print end of line, 'Thank you', end program.

Can we use if statement in while loop?

And to answer your questions, yes it's perfectly valid to nest if statements in a while loop.

What is exit criteria for while loop in Python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.