首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在具有多个条件的python中循环

如何在具有多个条件的python中循环
EN

Stack Overflow用户
提问于 2022-02-28 21:44:05
回答 3查看 147关注 0票数 0

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

代码语言:javascript
复制
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之间的数字,然后检查它是否在列表中。我已经在网上搜索过了,但是我找不到我错的地方。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-02-28 21:48:31

您的循环应该在n < 0n > 9时继续。

代码语言:javascript
复制
while n < 0 or n > 9:
    ...

根据德摩根定律,否定这一条件很可能是你的目的:

代码语言:javascript
复制
while not (0 <= n <= 9):
    ...
票数 1
EN

Stack Overflow用户

发布于 2022-02-28 21:56:07

你可以这样做:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2022-02-28 22:42:42

给你:)

代码语言:javascript
复制
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()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71301387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档