The Python Oracle

How to do while loops with multiple conditions

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 How To Do While Loops With Multiple Conditions
00:31 Accepted Answer Score 23
00:40 Answer 2 Score 3
00:52 Answer 3 Score 1
01:13 Answer 4 Score 0
01:26 Thank you

--

Full question
https://stackoverflow.com/questions/2146...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #logic

#avk47



ACCEPTED ANSWER

Score 23


Change the ands to ors.




ANSWER 2

Score 3


while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.




ANSWER 3

Score 1


Have you noticed that in the code you posted, condition2 is never set to False? This way, your loop body is never executed.

Also, note that in Python, not condition is preferred to condition == False; likewise, condition is preferred to condition == True.




ANSWER 4

Score 0


condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code

while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
    val,something1,something2 = getstuff()

    if something1 == 10:
        condition1 = True

    elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead    
    condition2 = True
# ihope it can be helpfull