while循环不在python中循环

sar*_*raw 0 python while-loop

简单的while循环,不按预期工作.我正在尝试创建一个模拟一个骰子的函数,并保持结果的总计,直到该总和> = m,此时它应该停止.我想知道最终总数是多少,以及到达那里需要多少卷.

目前,它推出的两倍,并报告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
Run Code Online (Sandbox Code Playgroud)

Abh*_*jit 6

看起来你对控制如何从函数返回以及如何返回值有误解.当前问题与您的while循环无关,而是如何处理函数的返回.

您应该了解可以有多个返回路径,但对于任何特定的执行,执行一个且仅一个返回,将忽略顺序路径中的任何后续返回.

此外,您需要一种捕获返回值的方法,它不能自动污染您的全局命名空间

因此,总结和解决您的问题,一个可能的出路将是

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
Run Code Online (Sandbox Code Playgroud)