如何在多个条件下循环 python

How to loop in python with multiple conditions

我目前正在学习 Python 基础知识并陷入了这个 While 循环:

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

我想要的是一个循环,该循环一直运行到用户输入 0 到 9 之间的数字,然后他们检查它是否在列表中。 我已经在网上搜索过了,但我找不到我错的地方。

你的循环应该在 n < 0 or n > 9:

时继续
while n < 0 or n > 9:
    ...

根据德摩根定律否定此条件可能是您的目标:

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

你可以这样做:

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

给你:)

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')

您现在要做的就是致电 class loop_with_condition()