Home > Enterprise >  How to loop in python with multiple conditions
How to loop in python with multiple conditions

Time:03-01

I'm currently studying Python basics and got stuck in this While loop:

numbers = [1, 3, 6, 9]
n = int(input('Type a number between 0 and 9: '))
while 0 > n > 9:
    n = int(input('Type a number between 0 and 9: '))
if n in numbers:
    print('This number is on the number list!')

enter image description here

What I want is a loop that runs till the user introduces a number between 0 and 9 and them check if it is on the list. I've already searched for it in the web but I can't find where I'm wrong.

CodePudding user response:

Your loop should continue while n < 0 or n > 9:

while n < 0 or n > 9:
    ...

The negation of this condition, by de Morgan's laws, is probably what you were aiming for:

while not (0 <= n <= 9):
    ...

CodePudding user response:

You can do this:

def loop_with_condition():
    numbers = [1, 3, 6, 9]
    while True:
        n = int(input('Type a number between 0 and 9: '))
        if n < 0 or n > 10:
            print('Out of scope!')
            break
        if n in numbers:
            print('This number is on the number list!')


if __name__ == '__main__':
    loop_with_condition()
  • Related