Multiple conditions in while loop python

by use of the logical operators

Multiple conditions in while loop python

Or even use the 'or' operator ( || ) ;P while ( (x>42) || (y<42) || (n==42) ) { /* ... */ }

Multiple conditions in while loop python

since a while loop only runs if its condition is true, you can connect multiple conditions with the Boolean and (&&) while(condition1 && condition2 && condition3) { // do something }

Multiple conditions in while loop python

Even you can use both. while(((5 > y) || (x < 5)) && (z != 10)) { /* my statements... */ }

Multiple conditions in while loop python

You can use logical operators (&&, ||, !) or even the conditional operators (?:)

Multiple conditions in while loop python

It's pretty much been answered albeit without much explanation: || if you want either condition being true to keep it running, && if you want either condition being false to end it. I think you need an explanation, too... With OR (||), we say loop if ANY of the following are true. With AND (&&), we're saying EVERY one of these must be true. I would like to add that if one condition or all conditions are false for && and || respectively, all code in your while block will not run. This could also be where you're going wrong (no code posted). If this is the case, a do-loop is better. Syntax: do { /* your code */ } while (condition) || (condition); Hopefully this better clarifies things.

Multiple conditions in while loop python

Multiple conditions in while loop python

@Jamie, I agree with your solution but I myself made a lot of use in my past programming profession that included the CASE structure in it to execute the DO WHILE loop. To exit the WHILE LOOP, I used a simpel FOR ELSE condition to change the WHILE condition to exit the LOOP. It is nice to see that some of you go the extra step to help a fellow programmer...

Multiple conditions in while loop python

And yet another method: You can combine if/case statements within your loop with the 'continue' command to add flow changes within a loop.

Multiple conditions in while loop python

Suppose in a while loop, you have two conditions, and any one needs to be true to proceed to the body, then in that case you can use the || operator between those two conditions, and in case you want both to be true, you can use && operator.

Multiple conditions in while loop python

By using if statements and logical operators such as &&, 11,!

Multiple conditions in while loop python

Multiple conditions in while loop python

using logical operators ✌

Multiple conditions in while loop python

Multiple conditions in while loop python

link then using Boolean operators

Multiple conditions in while loop python

use or function while ( (a>10) || (b<10) || (m==10) ) { /* have a fun */ }

Multiple conditions in while loop python

You can use logical operators i.e. or,and,not to combine these conditions to get the required outputs.

Multiple conditions in while loop python

Multiple conditions in while loop python

while(condition) { while(condition) { while(condition) { } } }

Multiple conditions in while loop python

f*********************************k

Multiple conditions in while loop python

  • Python while loop syntax
  • Example-1: How to repeat python while loop a certain number of times
  • Example-2: How to exit while loop in Python based on user input
  • Example-3: Using python while loop with a flag
  • Example-4: When to use continue in a python while loop
  • Example-5: When to use break in a python while loop
  • Example-6: How to use break with while and else condition in Python
  • Example-7: How to use nested while loop in Python
  • Example-8: How to use python while loop with multiple conditions
  • Summary
  • Further Readings

In this article we will learn how to keep programs running as long as users want them to. We will use Python while loop to keep programs running as long as certain conditions remain true. The while loop is used when you need your logic repeated until a certain condition is met, usually because you don't know how many times it will take. This could be because you are waiting for some condition to be met, like a timer expiring or a certain key press.

Python while loop syntax

The for loop takes a collection of items and executes a block of code once for each item in the collection. On the other hand, the while loop runs as long as, or while, a certain condition is true.

The general syntax of while loop would be:

while test:                     # Loop test
    handle_true()               # Loop body
else:                           # Optional else
    handle_false()              # Run if didn't exit loop with break

The while statement consists of a header line with a test expression, a body of one or more normally indented statements, and an optional else part that is executed if control exits the loop without a break statement being encountered.

Example-1: How to repeat python while loop a certain number of times

In this example we will write a code to repeat python while loop a certain pre-defined number of times. The general syntax to achieve this would be:

i = 0
while i < n:
    # do something here
    i += 1

It is important that in such condition we increment the count in each loop to avoid repeating the same loop. Here I have an example script where we want the while loop to be run 5 times. So we take a variable "count" and assign the value as 1. Next we put a condition with while loop to run the loop as long as the value of count is less than or equal to 5. This was the loop will run exactly 5 times. It is important that we increment the value of count after each iteration ends.

#!/usr/bin/env python3

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

Output from this script:

Multiple conditions in while loop python

Example-2: How to exit while loop in Python based on user input

We can use input() function to collection some input from a user in Python programming language. Now this can be a repetitive task such as asking for password and unless both password attempt matches, the loop should continue to ask the user.

Here is our example script, where we ask for password two times to the user. If both password match then we exit the python while loop or else the code will continue to ask for password till eternity.

#!/usr/bin/env python3

while True:
    pwd1 = input("Enter new password: ")
    pwd2 = input("Retype your password: ")
    if pwd1 == pwd2:
        print('Perfect!!')
        break
    print("Both password don't match, try again..")

Output from this script:

Multiple conditions in while loop python

Example-3: Using python while loop with a flag

In the previous example, we had the program perform certain tasks while a given condition was true. But what about more complicated programs in which many different events could cause the program to stop running?

We can write our programs so they run while the flag is set to True and stop running when any of several events sets the value of the flag to False. As a result, our overall while statement needs to check only one condition: whether or not the flag is currently True.

Let's add a flag to our previous example, we will call this flag as active:

#!/usr/bin/env python3

# Set the flag as True initially
active = True

while active:
    pwd1 = input("Enter new password: ")
    pwd2 = input("Retype your password: ")
    if pwd1 == pwd2:
        print('Perfect!!')
        ## Instead of using break we set the flag active as False
        active = False
    ## Now we need an else condition as we are not breaking
    ## out of the while loop
    else:
        print("Both password don't match, try again..")

Output from this script:

Multiple conditions in while loop python

Example-4: When to use continue in a python while loop

Rather than breaking out of a loop entirely without executing the rest of its code, you can use the continue statement to return to the beginning of the loop based on the result of a conditional test.

For example, consider a loop that counts from 1 to 10 but prints only the odd numbers in that range:

#!/usr/bin/env python3

num = 

# If num is less than 10
while num < 10:
    # increment num by 1
    num += 1
    ## Check for divided by 2 gives a remainder
    ## if remainder is zero, then it is an even number
    if num % 2 == 0:
        # If the loop enters here means even num found
        # so skip this num and continue with the loop
        continue
    # if condition was no match so print odd number
    print(num)

First we set num to 0. Because it’s less than 10, Python enters the while loop. Once inside the loop, we increment the count by 1, so num is 1. The if statement then checks the modulo of num and 2. If the modulo is 0 (which means num is divisible by 2), the continue statement tells Python to ignore the rest of the loop and return to the beginning. If the num is not divisible by 2, the rest of the loop is executed and Python prints the current number.

Output from this script:

Multiple conditions in while loop python

Example-5: When to use break in a python while loop

I have already used break statement in one of my examples above. To exit a while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break statement. The break statement directs the flow of your program; you can use it to control which lines of code are executed and which aren’t, so the program only executes code that you want it to, when you want it to.

For example here I have an infinite while loop where I ask user for some text input. Then the script will capitalize the first letter of the text unless user decides to quit by providing "q" as an input.

#!/usr/bin/env python3

while True:
    text = input("String to capitalize [type q to quit]: ")
    if text == "q":
        break
    print(text.capitalize())

Here we read a line of input from the keyboard via Python’s input() function and then print it with the first letter capitalized. We break out of the loop when a line containing only the letter q is typed:

Multiple conditions in while loop python

Example-6: How to use break with while and else condition in Python

If the while loop ended normally (no break call), control passes to an optional else. You use this when you’ve coded a while loop to check for something, and breaking as soon as it’s found. The else would be run if the while loop completed but the object was not found.

In this example script, we will look out for even numbers from a provided list of numbers.

#!/usr/bin/env python3

numbers = [1, 3, 5, 9]
position = 

while position < len(numbers):
    number = numbers[position]
    if number % 2 == :
        print('Found even number', number)
        break
    position += 1
# if break is not called then loop enters else condition
else:
    print('No even number found')

Here also we are checking for a number divisible by 2 with 0 remainder. If no such number found then the loop enters else condition of while loop. Output from this script:

~]# python3 example-5.py
No even number found

Example-7: How to use nested while loop in Python

Python allows you to nest loops. A nested loop is simply a loop that resides inside of another loop. There are lots of good reasons to use nested loops, from processing matrices to dealing with inputs that require multiple processing runs.

The syntax to use a nested while loop would be something like:

i = 
while i < n:

    j = 
    while j < m:
        # do something in while loop for j
        j += 1

    # do something in while loop for i
    i += 1

Suppose you are given the task of implementing a program that accepts a number from a user and then determines whether it is a prime number. The program also has to continue to accept values from the user until the user enters a zero.

To determine if a number is prime, you divide it by the values beginning at 2 and ending at the number. If none of those values results in a number without a remainder, the value is prime; if any one of the values does result in a number without a remainder, the number is not prime.

#!/usr/bin/env python3

while True:
    number = int(input("Enter a number: "))
    if number == :
        break
    divisor = 2
    isPrime = True
    while divisor < number:
        # break the loop if prime number
        if number % divisor == :
            isPrime = False
            break
        divisor += 1

    if isPrime == True:
        print("The value ", number, " is prime")
    else:
        print("The value ", number, " is NOT prime")
print("Done")

Output from this script:

~]# python3 example-6.py
Enter a number: 12
The value  12  is NOT prime
Enter a number: 14
The value  14  is NOT prime
Enter a number: 23
The value  23  is prime

Example-8: How to use python while loop with multiple conditions

In al the previous examples, we have defined a single condition with our python while loop. But it is also possible that there are multiple conditions to execute the loop. Here is one such example:

#!/usr/bin/env python3

i = 1
j = 10

while i < 5 and j > 1:
    i += 1
    j -= 1
    print(i, j)

Here we have added a condition to run the loop as long as the value of i is less than 5 and value of j is greater than 1. Inside the loop we are incrementing the value of i by 1 and decrementing the value of j in each iteration. Here is the output from this script:

Multiple conditions in while loop python

Here are some more syntax to understand the usage of multiple conditions in python while loop:

while (a != b) and (a != c) and (a != d):
  # do something

while (a != b) or (a != c) or (a != d):
  # do something

while a not in { b, c, d }:
  # do something

Summary

In this article you learned how to use python while loop to make your programs run as long as your users want them to. You saw several ways to control the flow of a while loop by setting an active flag, using the break statement, and using the continue statement. You learned how to use a while loop in nested format with examples and syntax. It is recommended to use the while loop with caution when using with endless loop. It is important that you use a counter and always increment the counter at the end of iteration.

Further Readings

The while statement in Python
break and continue Statements, and else Clauses on Loops

Related Searches: python break while loop, python while loop example, python exit while loop, nested while loops python, how to end a while loop in python, python infinite while loop, python while loop multiple conditions, python while loop user input, python break out of while loop, python while loop syntax

Can I have 2 conditions in while loop Python?

Grouping multiple conditions in Python Python multiple conditions in an if statement requires several true conditions at the same time. In this example, we can easily use the multiple logical operators in the while loop condition.

Can you have 2 conditions in a while loop?

Using multiple conditions As seen on line 4 the while loop has two conditions, one using the AND operator and the other using the OR operator. Note: The AND condition must be fulfilled for the loop to run. However, if either of the conditions on the OR side of the operator returns true , the loop will run.

How many conditions can a while loop have in Python?

Logical AND Operator Here, the while loop has two conditional expressions, A and B, that it needs to evaluate.

How do you write multiple statements in for loop in Python?

If you want to execute multiple statements for every iteration of the for loop, then indent them accordingly (i.e put them in the same level as the print command).