我有以下代码:
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/