Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 593
kirill_igum Avatar asked Mar 07 '11 03:03

kirill_igum


People also ask

How do you jump a loop in Python?

The break and continue statements in Python are used to skip parts of the current loop or break out of the loop completely. The break statement can be used if you need to break out of a for or while loop and move onto the next section of code.

How do you jump two steps in a for loop in Python?

To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.

What command do you use to jump out of a for loop Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.


1 Answers

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
like image 118
kindall Avatar answered Oct 15 '22 09:10

kindall