0

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.

3 Answers3

1

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):
    ...
chepner
  • 497,756
  • 71
  • 530
  • 681
0

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()
0

Here you go :)

numbers = [1, 3, 6, 9]

class loop_with_condition:
    def __init__(self):
        self.num = int(input('Choose a number from 0 to 9: '))
        self.check()
    
    def check(self):
        if self.num not in numbers:
            print(f'Number {self.num} not in numbers')
            self.__init__()
            return
        else:
            print(f'Number {self.num} is in numbers')

All you got to do now is call the class loop_with_condition()