Skip to main content
 首页 » 编程设计

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

2025年01月19日11rubylouvre

我有以下代码:

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