Loops
"Write the first 100 numbers."
There are several assumptions implicit in this seemingly simple command. The first is that the student knows where to start, namely at number 1. The second assumption is that the student knows where to end, at number 100. And the third is that the student understands that they should count by 1.
In programming, this set of instructions may be executed with a loop.
There are three key components to most loops:
- The start of the loop
- The end of the loop
- The increment between numbers in the loop
Python distinguishes between two fundamental kinds of loops: while
loops, and for
loops.
The while Loops
In a while
loop, a designated segment of code repeats provided that a particular condition is true. When the condition evaluates to false, the while
loop stops running. The while
loops print out the first 10 numbers.
You could print the first 10 numbers by implementing the print
function 10 times, but using a while
loop is more efficient, and it scales easily. In general, it's not a good idea to copy and paste while coding. If you find yourself copying and pasting, there's probably a more efficient way. Let's have a look at the following example code block:
i = 1 while i <= 10: print(i) i += 1
You should get the following output:
1 2 3 4 5 6 7 8 9 10
You can break down the preceding code block and find out what's happening in concrete steps:
- Initialize the variable: Loops need to be initialized with a variable. The variable is going to change throughout the loop. The naming of the variable is up to you.
i
is often chosen because it stands for incrementor. An example isi = 1
. - Set up the while loop: The
while
loop starts with thewhile
keyword. Followingwhile
is the chosen variable. After the variable comes the condition that must be met for the loop to run. In general, the condition should have some way of being broken. When counting, the condition usually includes an upper limit, but it could also be broken in other ways, such asi != 10
. This line of code is the most critical piece of the loop. It sets up how many times the loop is expected to run. An example is whilei <= 10:
. - Instructions: The instructions include all indented lines after the colon. Anything could be printed, any function could be called, and any number of lines may be executed. It all depends on the program. As long as the code is syntactically correct, generally speaking, anything goes. This part of the loop is going to run over and over as long as the aforementioned condition is true. An example is
print(i)
. - Increment: The incrementor is a crucial part of this example. Without it, the preceding code will never stop running. It will print 1's endlessly because 1 is always less than 10. Here, you increment by 1, but you could also increment by 2, or any other number. An example is
i += 1
.
Now that you understand the separate pieces, you should look at how it works together:
- The variable is initialized as
1
. Thewhile
loop checks the condition.1
is less than or equal to10
.1
is printed.1
is added toi
. We increment toi = 2
. - After all indented code after the colon has run, the loop is executed again by returning to the
while
keyword. - The
while
loop checks the condition again.2
is less than or equal to10
.2
is printed to the console.1
is added toi
. We now increment toi = 3
. - The
while
loop checks the condition again.3
is less than or equal to10
.3
is printed to the console.1
is added toi
. We increment toi = 4
. - The while loop continues to increment and print out numbers until reaching the number 10.
- The
while
loop checks the condition.10
is less than or equal to10
.10
is printed to the console.1
is added toi
. Now, increment toi = 11
. - The
while
loop checks the condition.11
is not less than or equal to10
. We break out of the loop by moving beyond the indentation.Note
You will get stuck in infinite loops. It happens to everyone. At some point, you will forget to add the increment, and you will be stuck in an infinite loop. In Jupyter Notebooks, just
restart
the kernel.
An Infinite Loop
Now you should have a look at infinite loops. The following code snippet supports this topic:
x = 5 while x <= 20: print(x)
Python often runs very quickly. If something is taking much longer than expected, an infinite loop might be the culprit, as in the aforementioned code snippet. A developer here would be setting all the variables and conditions right to avoid the infinite loop case. An example of a well-written Python code is as follows:
x = 5 while x<= 20: print(x) x += 5
break
break is a special keyword in Python that is specifically designed for loops. If placed inside of a loop, commonly in a conditional, break
will immediately terminate the loop. It doesn't matter what comes before or after the loop. The break is placed on its own line, and it breaks out of the loop.
To practice, you should print the first number greater than 100
that is divisible by 17
.
The idea is that you are going to start at 101 and keep counting until you find a number divisible by 17
. Assume you don't know what number to stop at. This is where break comes into play. break
will terminate the loop. You can set our upper bound at some number that you know you will never reach and break out of the loop when you get there:
# Find first number greater than 100 and divisible by 17. x = 100 while x <= 1000: x += 1 if x % 17 == 0: print('', x, 'is the first number greater than 100 that is divisible by 17.') break
The x += 1
iterator is placed at the beginning of the loop. This allows us to start with 101. The iterator may be placed anywhere in the loop.
Since 101 is not divisible by 17
, the loop repeats, and x = 102
. Since 102
is divisible by 17
, the print
statement executes and we break out of the loop.
This is the first time you have used double indentation. Since the if
conditional is inside of a while
loop, it must be indented as well.
Activity 4: Finding the Least Common Multiple (LCM)
In this activity, you will find the LCM of two divisors. The LCM of two divisors is the first number that both divisors can divide.
For instance, the LCM of 4 and 6 is 12, because 12 is the first number that both 4 and 6 can divide. You will find the LCM of 2 numbers. You will set the variables, then initialize a while
loop with an iterator and a Boolean that is True
by default. You will set up a conditional that will break if the iterator divides both numbers. You will increase the iterator and print the results after the loop completes.
In this activity, using the following steps, you need to find the LCM of 24
and 36
.
The steps are as follows:
- Set a pair of variables as equal to
24
and36
. - Initialize the
while
loop, based on a Boolean that isTrue
by default, with an iterator. - Set up a conditional to check whether the iterator divides both numbers.
- Break the while loop when the LCM is found.
- Increment the iterator at the end of the loop.
Print
the results.You should get the following output:
The Least Common Multiple of 24 and 36 is 72.
Note
The solution for this activity can be found via this link.
Programs
You have been writing programs all through this book. Every chunk of executable code that can be saved and run on demand is a computer program. You have written programs that greeted users, and you just wrote a program to compute the LCM of a given number in Activity 4, Finding the Least Common Multiple (LCM).
Now that you have a lot of tools under our belt, you can combine them to write some pretty interesting programs. You know how to generate input from a user, we know how to convert the input into desired types, and you know how to use conditionals and loops to iterate through cases and print various results depending upon the outcome.
Later in the book, you will get into the details of saving and testing programs. For now, you should work on some interesting examples and exercises. For instance, in the next exercise, you will build a program step by step to identify perfect squares.
Exercise 18: Calculating Perfect Squares
The goal of this exercise is to prompt the user to enter a given number and find out whether it is a perfect square.
The following steps in this exercise will help you with this:
- Open a new Jupyter Notebook.
- Prompt the user to enter a number to see if it's a perfect square:
print('Enter a number to see if it\'s a perfect square.')
- Set a variable as equal to
input()
. In this case let's enter 64:number = input()
- Ensure the user input is a positive integer:
number = abs(int(number))
- Choose an iterator variable:
i = -1
- Initialize a Boolean to check for a perfect square:
square = False
- Initialize a
while
loop from-1
to the square root of the number:while i <= number**(0.5):
- Increment
i
by1
:i += 1
- Check the square root of the
number
:if i*i == number:
- Indicate that we have a perfect
square
:square = True
break
out of the loop:break
- If the number is
square
,print
out the result:if square: print('The square root of', number, 'is', i, '.')
- If the number is not a square, print out this result:
else: print('', number, 'is not a perfect square.')
You should get the following output:
The square root of 64 is 8.
In this exercise, you have written a program to check to see whether the user's number is a perfect square.
In the next exercise, you are going to build a similar program that will accept inputs from the user. You need to provide the best possible offer for a real estate and either accept or decline the offer.
Exercise 19: Real Estate Offer
The goal of this exercise is to prompt the user to bid on a house and let them know if and when the bid has been accepted.
The following steps in this exercise will help you with this:
- Open a new Jupyter Notebook.
- Begin by stating a market price:
print('A one bedroom in the Bay Area is listed at $599,000')
- Prompt the user to make an offer on the house:
print('Enter your first offer on the house.')
- Set
offer
as equal toinput()
:offer = abs(int(input()))
- Prompt the user to enter their best offer for the house:
print('Enter your best offer on the house.')
- Set
best
as equal toinput()
:best = abs(int(input()))
- Prompt the user to choose increments:
print('How much more do you want to offer each time?')
- Set
increment
as equal toinput()
:increment = abs(int(input()))
- Set
offer_accepted
as equal toFalse
:offer_accepted = False
- Initialize the
for
loop fromoffer
tobest
:while offer <= best:
- If the
offer
is greater than650000
, they get the house:if offer >= 650000: offer_accepted = True print('Your offer of', offer, 'has been accepted!') break
- If the
offer
does not exceed650000
, they don't get the house:print('We\'re sorry, you\'re offer of', offer, 'has not been accepted.' )
- Add
increment
tooffer
:offer += increment
You should get the following output:
In this exercise, you have prompted the user to bid for a house and let them know when and if the bid was accepted.
The for Loop
The for
loops are similar to while
loops, but they have additional advantages, such as being able to iterate over strings and other objects.
Exercise 20: Using for Loops
In this exercise, you will utilize for
loops to print the characters in a string in addition to a range of numbers:
- Open a new Jupyter Notebook.
- Print out the characters of 'Portland':
for i in 'Portland': print(i)
You should get the following output:
P o r t l a n d
The
for
keyword often goes with the in keyword. Thei
variable is generic. The phrase,for i in
, means that Python is going to check what comes next and look at its individual components. Strings are composed of characters, so Python will do something with each of the individual characters. In this particular case, Python will print out the individual characters, as per theprint(i)
command.What if we want to do something with a range of numbers? Can
for
loops be used for that? Absolutely. Python provides another keyword,range
, to access a range of numbers.range
is often defined by two numbers, the first number, and the last number, and it includes all numbers in between. Interestingly, the output ofrange
includes the first number, but not the last number. You will see why in a minute. - You use a lower bound of
1
and an upper bound of10
with range toprint
1
-9
:for i in range(1,10): print(i)
You should get the following output:
1 2 3 4 5 6 7 8 9
The range does not print the number
10
. - Now use
range
with one bound only, the number10
, to print the first ten numbers:for i in range(10): print(i)
You should get the following output:
0 1 2 3 4 5 6 7 8 9
So,
range(10)
will print out the first10
numbers, starting at0
, and ending with9
.Now let's say that you want to count by increments of
2
. You can add a third bound, a step increment, to count up or down by any number desired.Use a step increment to count the even numbers through 10:
for i in range(1, 11, 2): print(i)
You should get the following output:
1 3 5 7 9
Similarly, you can count down using negative numbers, which is shown in the next step.
- Use a step increment to count down from
3
to-1
:for i in range(3, 0, -1): print(i)
You should get the following output:
3 2 1
And, of course, you can use nested loops, which is shown in the next step.
- Now,
print
each letter of yourname
three times:name = 'Corey' for i in range(3): for i in name: print(i)
You should get the following output:
C o r e y C o r e y C o r e y
In this exercise, you have utilized loops to print any given number of integers and characters in a string.
The continue Keyword
continue
is another Python keyword designed for loops. When Python reaches the continue
keyword, it stops the code and goes back to the beginning of the loop. continue is similar to break
because they both interrupt the loop process, but break
terminates the loop, continue
continues the loop from the beginning.
Let's look at an example of continue
in practice. The following code prints out every two-digit prime number:
for num in range(10,100): if num % 2 == 0: continue if num % 3 == 0: continue if num % 5 == 0: continue if num % 7 == 0: continue print(num)
You should get the following output:
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Let's go through the beginning of the code. The first number to check is 10
. The first line checks to see if 10
can be divided by 2
. Since 2
does divide 10
, we go inside the conditional and reach the continue
keyword. Executing continue
returns to the start of the loop.
The next number that is checked is 11
. Since 2
,3
,5
, and 7
do not divide 11
, you reach the final line and print the number 11
.
Activity 5: Building Conversational Bots Using Python
You are working as a Python developer and you are building two conversational bots for your clients. You create a list of steps beforehand to help you out, as outlined in the following section. These steps will help you build two bots that take input from the user and produce a coded response.
The aim of this activity is to use nested
conditionals to build two conversational bots. In this activity, you will build two conversational bots. The first bot will ask the user two questions and include the user's answer in each of its follow-up responses. The second bot will ask a question that requires a numerical answer. Different responses will be given to a different number of scales. The process will be repeated for a second question.
The steps are as follows:
For the first bot, the steps are as follows:
- Ask the user at least two questions.
- Respond to each answer. Include the answer in the response.
For the second bot, the steps are as follows:
- Ask a question that can be answered with a number scale, such as "
On a scale of 1-10…
". - Respond differently depending on the answer given.
- State a different question following each answer that can be answered with a number scale.
- Respond differently depending on the answer given.
Note
The second bot should be written with nested conditionals.
Hint - casting may be important.
The expected output for bot 1 is as follows:
We're kindred spirits, Corey.Talk later.
The expected output for bot 2 is as follows:
Note
The solution for this activity can be found via this link.