while loop not looping in python -



while loop not looping in python -

simple while loop, not working expected. trying create function simulate roll of die, , maintain running total of result, until total >= m, @ point should stop. want know final total is, , how many rolls took there.

currently rolls twice, , reports sum of 9. have checked code outside loop , should (that is, these 3 lines: r = rdm.randint(1,6), tot += r, rolls.append(r)).

what missing??

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

it seems have misconception on how command returns function , how homecoming values. current issue nil pertinent while loop rather how processing returns function.

you should understand there can multiple homecoming paths particular execution, one , 1 homecoming executed, subsequent returns in sequential path ignored.

also, need way capture homecoming values , cannot automatically pollute global namespace

so summarize , solve problem, possible way out be

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

python while-loop

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -