while 循环不在 python 中循环

while loop not looping in python

简单的 while 循环,未按预期工作。我正在尝试创建一个函数来模拟掷骰子,并保留 运行 结果的总数,直到总数 >= m,此时它应该停止。我想知道最后的总数是多少,需要多少卷才能到达那里。

目前roll了两次,报和为9。我检查了循环外的代码,它做了它应该做的(也就是这3行:r = rdm.randint(1,6), tot += r, rolls.append(r)).

我错过了什么??

def roll(m):
    rolls = []
    tot = 0
    while tot < m:
        r = rdm.randint(1,6)
        tot += r  
        rolls.append(r)
    return tot
    return rolls
    return r

m=100    
roll(m)    
print "The number of rolls was", len(rolls)  
print "The total is", tot

您似乎对如何从函数控制 return 以及如何 return 值有误解。当前的问题与您的 while 循环无关,而是与您如何处理函数中的 returns 有关。

你应该明白可以有多个 return 路径但是对于任何特定的执行,一个并且只有一个 return 被执行,任何后续的 returns在顺序路径中被忽略.

此外,您需要一种方法来捕获 return 值并且它 不能自动污染您的全局名称空间

所以总结和解决你的问题,一个可能的出路是

def roll(m):
    rolls = []
    tot = 0
    while tot < m:
        r = rdm.randint(1,6)
        tot += r  
        rolls.append(r)
    return tot, rolls, r
tot, rolls, r = roll(m) 
print "The number of rolls was", len(rolls)  
print "The total is", tot

这在一般情况下应该可以工作,但是您在一行中为一个函数使用多个 return 语句——这是行不通的。函数计算 return 的那一刻,该函数停止触发。如果你想return多个值,return一个元组:

def roll(m):
    rolls = []
    tot = 0
    while tot < m:
        r = rdm.randint(1,6)
        tot += r  
        rolls.append(r)
    return tot, rolls, r

m=100    
a, b, c = roll(m)    
print "The number of rolls was", len(b)  
print "The total is", a

您只能有一个 return 声明。用逗号分隔您的 return 值,并在您使用多重赋值调用函数时将它们分配给变量。

return tot, rolls, r

当您调用函数时:

tot, rolls, r = roll(m)