while Loops

So far with loops all of them have gone all the way through a specified list. That is a requirement of the for loop. However, this can often be too restrictive. A Python while loop behaves similarly to common English usage. If someone says:

While your tea is too hot, add an ice cube.

To follow through with this scenario, you would first test the tea. If it was indeed too hot, you would add a little ice. Then you would test it again. If it is still too hot, you would add more ice. As long as you tested and found that the tea was too hot, you would add more ice.

Python has similar syntax:

while condition is True:

indented Block of code

Setting up the previous example in Python format:

while your tea is too hot:

add a cube of ice

Let's make this example a little more concrete by using some actual temperatures. Suppose the tea starts at a temperature of 115 degrees Fahrenheit. It'll be too hot until the temperature drops to 112 degrees. Adding an ice cube will drop the temperature one degree. We will test the temperature each time as well as providing the temperature BEFORE reducing the temperature. The Python code for this is as follows:

1 temperature = 115 #setting the initial value of the variable

2 while temperature >112: #creating the condition for the loop

3 print temperature #indented; will display current temp each time

4 temperature -= 1 #lowering the temperature one degree

5

6 print ('The tea is cool enough') #not indented; will execute AFTER

#the loop completes

Each time the computer reaches the end of the indented block after the while heading, it will return to the while heading for another test.

Each time the end of the indented loop body is reached, execution returns to the while loop heading for another test. When the test is finally false, execution jumps past the indented body of the while loop to the next sequential statement.

A final structure of the Python while loop:

initialization of variable

while continuation Condition:

do main action to be repeated

prepare variables for next time through the loop

Flow of while loop:

Test yourself #1. What is the output of the following code:

1 i = 4

2 while i < 9:

3 print (i)

4 i += 2

Test your self #2. What is the output of the previous code with a slight variation, switching the order in the loop body.

1 i = 4

2 while i < 9:

3 i += 2

4 print (i)

The sequence order is important. The variable i is increased before it is printed, so the first number is 6. Another common error is to assume that 10 will not be printed, since 10 is past 9, but the test that may stop the loop is not made in the middle of the loop. Once the body of the loop is started, it continues to the end, even when i becomes 10.

Test yourself #3. How many times will the loop be executed and what is the output of the following code?

1 number = 6

2 sum = 0

3 while number > 0:

4 sum += number

5 number -= 2

6 print ("The final sum is", sum)

Solutions to TY's 1-3

while Loop Problem

Sometimes they do not stop!! This is only really a problem if your intent is to keep looping until the end of time. Here is an example of an infinite loop, see if you can determine why:

1 some_num = 10 #initialize looping variable

2 while some_num >= 10: #create the condition for looping

3 print some_num

4 some_num += 1 #increase the variable by one each time

The condition, for looping, is that the variable have a value greater than, or equal to, 10. Since the variable starts at 10 the loop is initially executed. Each time through the loop the value of the variable increases by 1. Therefore the condition of the loop will never be False and the loop will continue infinitely.

Use the Ctl-C keyboard combination to break out of an infinite loop.

To avoid this problem, here are a few suggestions to follow:

1. Make sure that a while-loop is the best option. Often times a for-loop could be used.

2. Review your while statements and make sure that the Boolean test will become False at

some point.

3. When in doubt, use a print statement at the top and bottom of you while-loops body to see

what it's doing.

Concept Check

At this point please take the concept check below. You only get one opportunity so please be sure you are ready. There'll be no retakes!!!

Concept Check - while Loops

while-Loop Exercises, Pt 1

Looping Until User Wants to Quit

A common operation, particularly in game development, is to loop until the user performs a request to quit.

1 quit = "a" #initializing the loop variable

2 while quit != "n":

3 print ("Hello World") #do this

4 quit = str(input("Do you want to quit? "))

5 #input from user on whether to

6 #continue

We can include a menu of options, in the loop, for the user to choose from until they decide to quit:

1 # Give the user some context.

2 print("\nWelcome to the nature center. What would you like to do?")

3 # Set an initial value for choice other than the value for 'quit'.

4 choice = ''

5 # Start a loop that runs until the user enters the value for 'quit'.

6 while choice != 'q':

7 # Give all the choices in a series of print statements.

8 print("\n[1] Enter 1 to take a bicycle ride.")

9 print("[2] Enter 2 to go for a run.")

10 print("[3] Enter 3 to climb a mountain.")

11 print("[q] Enter q to quit.")

12

13 # Ask for the user's choice.

14 choice = input("\nWhat would you like to do? ")

15

16 # Respond to the user's choice.

17 if choice == '1':

18 print("\nHere's a bicycle. Have fun!\n")

19 elif choice == '2':

20 print("\nHere are some running shoes. Run fast!\n")

21 elif choice == '3':

22 print("\nHere's a map. Can you leave a trip plan for us?\n")

23 elif choice == 'q':

24 print("\nThanks for playing. See you later.\n")

25 else:

26 print("\nI don't understand that choice, please try again.\n")

27

28 # Print a message that we are all finished.

29 print("Thanks again, bye now.")

Random Module

The random module provides access to functions that support many operations. Perhaps the most important thing is that it allows you to generate random numbers.

The random module is useful when we want the computer to pick a random number in a given range, pick a random element from a list, pick a random card from a deck, flip a coin etc.

Random functions

Below are a few of the random functions we are likely to use. More can be found at the website (see link in left column).

randint(lower, upper)

If we wanted a random integer, we can use the randint function. randint accepts two parameters: a lowest and a highest number. Generate integers between 1, 5. The first value should be less than the second. Note: the upper value IS included with random as opposed to range.

1 import random

2 for i in range(4): #display 4 random integers

3 print random.randint(0, 5)

Sample Output:

2

3

0

2

random()

random(), by default, uses 0 and 1.00 as parameters. If you want a larger number, you can multiply it. For example, a random number between 0 and 100:

1 import random

2 random.random() * 100

choice(sequence)

Generate a random value from a sequence.

1 import random

2 random.choice( ['red', 'black', 'green'] ).

or

1 import random

2 myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"]

3 print random.choice(myList)

Possible output: False

shuffle(sequence)

The shuffle function, shuffles the elements in list in place, so they are in a random order.

1 import random

2 x=[]

3 for i in range(10)

4 x.append(i)

5 print (x)

6 random.shuffle(x)

7 print (x)

Possible Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[9, 2, 7, 0, 4, 5, 3, 1, 8, 6]

randrange(start, stop[, step])

Generate a randomly selected element from range(start, stop, step).

1 import random

2 for i in range(3):

3 print random.randrange(0, 101, 5)

Possible Output:

15

70

30

concept check #2, while-Loops and Random Module

while-Loops Exercises, Pt 2