我目前正在学习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!')我想要的是一个循环,直到用户引入一个介于0到9之间的数字,然后检查它是否在列表中。我已经在网上搜索过了,但是我找不到我错的地方。
发布于 2022-02-28 21:48:31
您的循环应该在n < 0或n > 9时继续。
while n < 0 or n > 9:
...根据德摩根定律,否定这一条件很可能是你的目的:
while not (0 <= n <= 9):
...发布于 2022-02-28 21:56:07
你可以这样做:
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()发布于 2022-02-28 22:42:42
给你:)
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')现在要做的就是调用类loop_with_condition()
https://stackoverflow.com/questions/71301387
复制相似问题