in python for loop,, jump over values
time=0
gold=0
level=1
for time in range(100):
gold+=开发者_如何学编程level
if gold>20*level:
level+=1
time+=10
with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those 20s (or 20 steps) in the loop? this works in c++, i'm not sure how to do it in python.
Don't do it in range(100)
. The for
loop doesn't offer a way to skip ahead like that; time
will be set to the next value in the list regardless of what you change it to in the body of the loop. Use a while
loop instead, e.g.
time = 0
while time < 100:
gold += level
if gold > 20 * level:
level +=1
time += 10
time += 1
time
will continually get overwritten each loop iteration, so time+=10
will not have the desired effect. You can convert the loop back into a C style loop using while
and explicit mutation of the time
variable or you could be fancy and setup an iterator which allows skipping ahead arbitrary values.
Your assignment to time
on the last line has no effect. At the top of the loop, time
is immediately assigned to the next value yielded by range
. But why is this a loop at all, can't you just do the calculations outright?
精彩评论