PYCS 06 - Repeating Things - Colaboratory
PYCS 06 - Repeating Things - Colaboratory
This Python Notebook is part of a sequence authored by Timothy R James - feel free to modify, copy,
share, or use for your own purposes.
So far, we have covered how to create variables, how to work with some basic data types, and how
to make decisions in our program. However, we will need more tools to solve problems. One of
those tools is iteration.
In any programming language, we'll need to be able to iterate - basically, we will need to repeat
statements while a condition is true. One of the great things about computers is that they can
easily do something over and over again; loops in Python allow us to do just that. We'll start with
the most straightforward loop - the while loop.
While Loops
The simplest loop in Python is the while loop. If you read the code out loud, while loops work
pretty much exactly how they sound. I.e., they repeat iteration while some condition continues to be
met.
In a while loop, as long as the evaluated condition is True , the indented code block will be
executed. At the end of the indented code block, the condition is evaluated again. As long as it
continues to be True , the indented block will continue to execute.
i = 0
print('The numbers 0 through 4:')
while i < 5:
print(i)
# We'll add 1 to i each time; the statement below is equivalent to i = i + 1
i += 1
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 1/6
1/12/23, 1:54 PM PYCS 06 - Repeating Things - Colaboratory
Note that a while loop kind of starts like an if statement; if the evaluated condition is not True ,
the while loop may never execute. For example, this code won't actually do anything.
i = 0
while i > 0:
print(i)
i += 2
Also note, we don't have to only increment by 1; we can use the += operator to increment by any
number.
i = 0;
print('These are all of the multiples of 5 between 5 and 100.')
while i < 100:
i += 5
print(i)
We also don't have to use while loops just for counting. We can use them for other purposes, too.
prompt = 'Enter a number, or enter "stop" to end.'
user_input = input(prompt)
while user_input != 'stop':
num = float(user_input)
double_num = num * 2
print('Double ' + str(num) + ' is ' + str(double_num))
# This last statement is important. We'll discuss why in the next section.
user_input = input(prompt)
At this point you may have already encountered a problem that plagues programmers of all
experience levels: the infinite loop. Infinite loops occur when the condition in a loop is always met.
This happens frequently with while loops when someone forgets to modify a variable or create
some condition that terminates the program. The code below will cause an infinite loop; you'll need
to press the stop button to the left of the code to exit.
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 2/6
1/12/23, 1:54 PM PYCS 06 - Repeating Things - Colaboratory
i = 0
while i < 1000:
# Whoops! We forgot to increment i.
print(i)
The problem with infinite loops is that they can be hard to detect; if you're not printing anything or
showing the user any output, they just appear like the computer is moving along, doing whatever it
needs to - despite the fact that it is just spinning in a circle.
One example of this is counting backwards when you intend to count forwards. Note that i -= 1
is the same as i = i - 1 ; it works just like i += 1 , except with subtraction. When we use it here,
we end up in an infinite loop that doesn't produce any output.
i = 0
while i < 1000:
# This probably should have been i += 1; instead, we used i -= 1
i -= 1
Another error you might sometimes encounter is when you create a loop, but the condition is never
met. You might accidentally test for a condition in the opposite way, like in the code below.
i = 500
print("Let's count backwards from 500 by 10s.")
# This should probably be i > 0.
while i < 0:
print(i)
i -= 10
print('All done!')
Breaking
Breaking isn't as severe as it sounds. It's just breaking out of a loop's execution. We use the break
keyword to stop executing a loop immediately.
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 3/6
1/12/23, 1:54 PM PYCS 06 - Repeating Things - Colaboratory
num = 1
print("Let's count to a billion!")
while num < 1000000000:
print(num)
num += 1
if num > 10:
# This stops us from going too far.
print('On second thought, a billion is too many.')
break
We could rewrite our example from above, where we get user input and double it, to use a break
statement, like this.
prompt = 'Enter a number, or enter "stop" to end.'
user_input = ''
while user_input != 'stop':
user_input = input(prompt)
if user_input == 'stop':
break
num = float(user_input)
double_num = num * 2
print('Double ' + str(num) + ' is' + str(double_num))
Continuing
In addition to the break statement, which immediately ends the loop, there is also a continue
statement, which will end only the current iteration of the loop. When you use continue , the rest of
the indented block of code is simply skipped and the condition is checked again.
i = 0
print('Here is a slow way to compute every even number between 2 and 30.')
while i <= 30:
i += 1
if i % 2 != 0:
continue
print(i)
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 4/6
1/12/23, 1:54 PM PYCS 06 - Repeating Things - Colaboratory
continue statements can be combined with break statements, like you see below.
user_input = ''
while user_input != 'quit':
user_input = input("Enter a number but don't enter 5! Enter 'quit' to end.")
if user_input == 'quit':
break
num = int(user_input)
if num == 5:
print('5 is no good!')
continue
print('Thank you! Your number is %s.' % num)
We can use while loops in a few different ways. Below, we're using a while loop to collect a bunch
of values from the user, and output the average of all of those values. We'll ask the user to enter a
number, or "done" when they're all done.
sum = 0
count = 0
prompt_string = 'Enter a number, or type "done" to end.'
user_input = input(prompt_string) # we will keep this as a string for now.
while user_input != 'done': # we will keep iterating until the user types done
input_number = float(user_input)
count += 1 # every iteration we add 1 to count
sum += input_number
user_input = input(prompt_string)
if count > 0:
average = sum / count
print('The average of all of those numbers is %s.' % average)
Try It!
Modify the code below so that it does not have an infinite loop.
countdown = 10
print('Counting down!')
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 5/6
1/12/23, 1:54 PM PYCS 06 - Repeating Things - Colaboratory
while countdown > 0:
print('%s...' % countdown)
countdown += 1
In the code below, the loop is never entered. Modify the code so that the loop is entered as you
would expect.
i = 500
print("Let's count backwards from 500 by 10s.")
while i < 0:
print(i)
i -= 10
Write Python code that asks the user for a number, then counts down from that number to 1.
prompt_string = 'Please enter a number.'
https://colab.research.google.com/drive/1krNmhFW-4z1yk4nJShuyjt1MdZmoiBT2?usp=sharing#printMode=true 6/6