python - While/Else 重新检查条件并循环

标签 python python-3.x

我有以下代码:

def check(onen,twon,threen,fourn,fiven):
while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
    return onen
else:
    onen = random.randint(1,45)

想问一下怎么做成这样:

def check(onen,twon,threen,fourn,fiven):
while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
    return onen
else:
    onen = random.randint(1,45)
        (check the condition on while again)

我想做这个循环:如果条件为假,检查并再次检查,直到它为真。

最佳答案

看来你把它弄反了。试试这个:

while not condition:
    change condition
return that

对于您的具体示例:

def check(onen, twon, threen, fourn, fiven):
    while not ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
        onen = random.randint(1,45)
    return onen

或更短:

def check(onen, twon, threen, fourn, fiven):
    while onen in (twon, threen, fourn, fiven):
        onen = random.randint(1,45)
    return onen

或者更短,没有循环(不过只适用于小范围):

def check(onen, twon, threen, fourn, fiven):
    return random.choice([x for x in range(1, 46) 
                          if x not in (twon, threen, fourn, fiven)])

但是请注意,这些都不会在函数外更改 onen 的值(当然,除非您执行 onen = check(...)).

关于python - While/Else 重新检查条件并循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225783/

相关文章:

Python 返回多个值并检查是否返回 False

python - 为什么我在 Ames Housing 数据集上执行的 Tensorflow 线性回归收敛速度非常非常慢?

python - 不会将csv数据存储到mysql表中吗?

python - 查找文本中单词列表中单词的出现次数

python - 基于类字段的生成函数?

python - input() 与 sys.stdin.read()

python - 名称错误 : name 'mobile' is not defined

python - 选择正确的 URL 来记录爬虫

python - 我们如何使用python从存储容器azure读取文件

Python tkinter : browse directory and save to new directory