Sometimes we want a program to keep doing something until a certain metric occurs. Imagine in your adventure game you are fighting a monster and that monster keeps attacking you until it has zero health (or worse you have zero health). We have few tools to help us iterate over a block of code like this.
Warning! As soon as you start to program loops you will surely accidentally program in an endless loop. This is a loop that will never stop and runs on your computer forever – at least until you terminate/break it. Imagine if I wrote x = 1. Then I said to add 1 to x until x was equal to zero. X will never equal zero, so the loop will go on and on forever making that number bigger and bigger.
For
#for weapons = ['Sword', 'Axe', 'Bow', 'Dagger'] for i in weapons: print(i)
While
#whille dragon_health = 50 while dragon_health > 0: print("the dragon attacked you!") print("You hit the dragon with your sword") dragon_health -= 10 #same a dragon_health = dragon_health - 10 print("Dragon Health: ", dragon_health) print()
Break and Continue
Break is used to exit a for loop or while loop. In the example below it is when health = 5.
health = 20 while health > 0: print("Your health is: ", health, "Good luck in the fight!") print("You suffered damage in battle, -1 health") print() #creates a blank line health -= 1 #same as health = health - 1 if health == 5: print("Your health is dangerously low at 5 you flee the fight!") break
Continue sends the program back to the beginning of the loop bypassing stuff in the block after.
#random 20 sided dice roll import random health = 50 while health > 0: roll20 = random.randint(1,20) print(roll20) if roll20 > 10: print("You avoided damage this round") print() continue print("Sorry you took damage!") health -= 2 print()
Wait a minute… what is that “import” thing I snuck in there you must be asking yourself? To keep things running efficiently they leave a lot of things out. Then when you need them your import them. Since a random number is not something you need all the time, just import the ability when you need it.
# Second Continue Example var = 10 while var > 0: var = var -1 if var == 5: continue print('Current variable value :', var) print("Good bye!")
The above program will print all the numbers from 9 to 0 but skip over the number 5.
While True – Almost infinite loop
Take a look at this example.
#this saying while true is equal to true while True: x = input("Please enter the magic words:") if x.strip() == 'open sesame': break else: print("Please try again.") print()
The first question people have when seeing this for the first time is “While true what? What is True?” This is a concept you should just accept without a lot of rhyme or reason. We are used to seeing something equate to true. In this case the meaning is just “is True == True.” The answer is yes and is always yes. So you have created an infinite loop. True will always be equal to True so the loop goes on forever unless it is broken. So we need a break statement to handle getting out of the While loop.
Else inside For loop (not always allowed in every programming language)
#for with an else # Prints out 1,2,3,4 for i in range(1,5): print(i) else: print("All done!")
Else inside a While loop
#while with an else # Prints out 0,1,2,3,4 and then it prints "count value reached 5" count=0 while(count<5): print(count) count +=1 else: print("All done!")
Hope that all makes sense. Iteration are very useful for plowing through large amounts of data!