~ A gentle introduction to while loops in Python


8 - A gentle introduction to While Loops in Python

While Loops in Python

We've covered some of the basics like variables and selection (if, elif, else) and it's now time to look at loops. Loops are one of the core constructs of programming and we see them in use all the time. When you fail to login correctly, you are thrown back into a loop that just keeps on asking you for the right combination of username and password. When you get it right, or exceed the number of tries, you break out of the loop and gain access to the program. So, let's look a little more at how loops work.

Download Python 3 here:



Task 1

1.First, run the code to see how it works! Think carefully about the declaration of x - this is the starting value. Then notice that the value of x is going up inside the loop => x =x+1. Notice, also that the while loop has a stopping condition which is when x<16. (so when x is more than 6, exit the loop!) You'll see that a while loop is used to print the numbers 0,1,2,3,4,5

2.Can you change the code slightly (two lines need to be changed) to make the code print out 1,2,3,4,5,6,7,8,9,10

Code

#The following code makes use of a while loop to print the numbers 0 to 5
#What do you need to change on lines 4 and 5 to get it to print 1,2,3,4,5,6,7,8,9,10
def main():
  x=0
  while x<6:
    print(x)
    x=x+1
    
    
main()

Task 2

1.Run the code below and note what it is trying to achieve. At the moment if the user writes open123, they are still stuck in the same loop. Why? We want "access granted" to be printed, so in other words, we need to exit out of the loop when the condition (==open123) is met.

2. Hint: Change one thing on line 8 to get this to work!

Code

#The following code asks the user to enter a secret password, IF they write open123, then access is granted, else they are stuck in a loop!
#You'll notice that even when the user enters "open123", it doesn not print "Access Granted". Change one thing on line 8 to get this to work!
def main():
  access=False
  while access==False:
    password=input("Enter secret password:")
    if password=="open123":
      access=False #Access can now be set to True, because the condition is met,and we can break out of the loop
  
  print("Access Granted") #note that this line is outside of the loop, so will be printed when you break out of the loop.
  access()
main()

Task 3

1. This loop appears to go on forever, can you fix it so that it only prints "Whoo, you're in a loop", three times?

2. All you need to do is change two things: (the greater sign and the number on line 5).

Code

#This loop appears to go on forever, can you fix it so that it only prints "Whoo, you're in a loop" three times?
#You only need to change two things (the greater sign and the number) on line 5.
def main():
   score=500 #initialise the score variable to 500
   while score>100: #condition for loop, while score is ABOVE 100
       print("Whoo, you're in a loop") #print this while above condition true
       score=score+1 #the score keeps going up for each loop round

main()

Task 4

1. This program prints "You are rich" while the number of gold coins variable is greater than 10. (it's starting value is 50!!)

2. You need to change ONE tiny thing on line 7 to make it print "You are rich", only FOUR times. Can you fix it?

Hint: Every while loop has a stopping condition otherwise it would, like this one, go on forever. In order to arrive at the stopping condition, the condition must be met, or worked toward. The no. of gold coins need to go DOWN (they started at 50) to reach the stopping condition of 10. So what would you change in the code to achieve this?

Code

#This program continues to print "You are rich", while the no of gold_coins is greater than 10!
#Change the code (you need to change just ONE tiny thing on line 7) to make it print only four times.
def main():
  gold_coins=50 #this is the starting value
  while gold_coins>10: #this is the stopping condition for the loop (while the gold_coins are above 10)
    print("You are rich!") #print this while the above condition is true
    gold_coins=gold_coins+10 #this makes the value of gold_coins go UP!!!!!!
main()    

Task 5

1.This program prints that the game is on, and the current score (that keeps going up) until the score is 9.

2. Change something on line 7 to make the game score go all the way up to exactly 20, and then stop!

3. Extension: See if you could change the variable score to 'health' instead. Make the health go DOWN, and when the health reaches 0, the loop breaks.

#What would you change on line 7 to make the game score go up to 20, and then stop!
import time

def main():
  score=0
  gameover=False
  while gameover==False and score<10:
    print("The game is on.....")
    print("Your score is:",score)
    time.sleep(1.1)
    score=score+1
    
main()

Final Challenge

Use your knowledge and skills from the completed tasks. Use the trinket below to complete your challenge.

Use a while loop to print out numbers from 1 to 20

Extension: Ask the user to input a number between 5 and 100. Use a while loop to print out numbers from 1 to the number (num) that the user input.

Answers

Coming soon!