Lesson 4 Looping
Lesson 4 Looping
Looping)
Introduction to Python Programming
Lesson 4: Looping (and Looping and
Looping)
➢
Lesson Overview
➢
Introduction
➢
The While Loop
➢
The For Loop
➢
Python Looping Extras
➢
Review
➢
Exercises
Introduction
➢
The last lesson we saw how to
make decisions in Python.
➢
Now we're going to turn our
attention to the repetition
structure, which is going to make
your programs flexible and useful
too.
➢
In a program it’s usual to want to
do an action or a block of code
over and over again – either for a
specified time or till some
condition is met.
3
Introduction
➢
How? Imagine a simple task such as printing a
word 10 times.
➢
Or maybe printing all the letters of the
alphabet.
➢
Each of these tasks can be done without the use
of loops.
➢
But without them, you're going to spend a lot of
time writing lines of code that look identical or
nearly identical to one another.
4
Introduction
➢
In both cases, your user is deciding how many times
something is happening inside your program.
Since this is done at run time, there's no way for you to
➢
➢
In this lesson, you’ll learn about Python's two looping
structures: while loops and for loops.
We'll discuss about how they're similar and how they're
➢
different.
➢
Then you’ll discover you some things you can use in
conjunction with these structures to give you more
options with your programs.
6
The while Loop: The Basics of the While
Loop
user to decide?
➢
Even with the ability to copy and paste code, are
you really going to want to create 10,000 lines of
print statements?
➢
But with a loop structure, you have another
option.
7
The while Loop: The Basics of the While
Loop
➢
Here’s the structure of while,
a basic loop. The Python
syntax for this follows:
➢
The syntax look a bit similar
to the if statement.
➢
With the while statement the
code runs over and over until
the condition becomes false.
8
The while Loop: The Basics of the While
Loop
Try this:-
➢
➢
You can easily modify the code to print numbers
to 100 or 1000000
But what is happening here?
➢
9
The while Loop: The Basics of the While
Loop
➢
The number variable initially
stores a value of 1.
➢
When the program gets to the
while statement for the first
time, 1 is compared to 5.
Since 1 is less than or equal to
➢
10
The while Loop: The Basics of the While
Loop
number becomes 6.
➢
At that time, the condition
becomes false because 6 is not
less than or equal to 5.
➢
The program therefore exits the
loop and moves to the first
statement after the loop that
isn't indented.
➢
This statement is the goodbye
to the user.
This is quite useful!
➢
11
The while Loop: Infinite Loops
➢
There's one critical thing to
note about while loops: you
need to provide some way of
making it possible for your
condition to become false.
➢
If you don't, you'll be stuck in
an infinite loop.
➢
Try commenting out the
increment line with #
You can exit out of the loop
➢
by pressing Ctrl+C.
12
The while Loop: Conditional Loops
The while loop you wrote earlier used a variable that was essentially
➢
counting.
➢
That is, you used the number variable to keep track of the number of
times you went through the loop.
This is known as a counter controlled loop (not “counter” in the sense
➢
13
The while Loop: Conditional Loops
➢
The output should look
something like this:-
14
The while Loop: Examples
➢
Write a program that prints all the even numbers
from 1 to 100.
Using conditions and with out using them.
➢
15
The For Loop: The Basics of the For Loop
➢
The for loop is essentially a shorthand version of the while
loop.
The shorthand comes because you don't have to worry about
➢
16
The For Loop: The Basics of the For Loop
➢
The for loop is a
powerful tool that you
use in a variety of
situations with a lot of
different structures.
➢
For now, though, let’s
start simple and use a
for loop to go through a
range of numbers.
➢
Python has a built-in
function called range.
17
The For Loop: The Basics of the For Loop
➢
What's happening here? When Python gets to the for statement the first time, it
looks at the range statement to create a list of values from 1 to 5.
➢
Note that in Python, there is a data structure called a list that you’ll learn about
later in the course.
For now, just think of this as a simple list of values: 1, 2, 3, 4, 5.
➢
Python creates this list and takes the first number (the value 1) out of the list
➢
executed.
Arriving at the end of the loop, Python goes back to the for statement and takes
➢
the next value (the number 2) out of the list and stores it in the number variable.
This pattern continues until there are no more items in the list.
➢
19
The For Loop: The Basics of the For Loop
➢
Unlike the while loop,
notice how you don't
need to worry about
updating the variable so
that some condition
eventually becomes
false.
➢
Instead, it just goes
through every element
in the list. Most
important, it can't get
stuck in an infinite loop.
20
The For Loop: Passing the Number of
Iterations
➢
In addition to passing
the start and end
numbers, you can also
pass the number of
numbers you want
printed.
➢
Note that range will
always start at 0 and go
through one less than
the value you pass it.
21
The For Loop: Passing the Number of
Iterations
22
The For Loop: Specifying Descending
Values
➢
But what if you want to print them in decreasing
order?
And what if you just want to print every other
➢
number?
➢
How will the range function handle such a task?
Here is an extended syntax for the range object
➢
23
The For Loop: Specifying Descending
Values
➢
Using the third parameter also enables you to
create a list of descending values. For example,
to get the numbers from 5 to 1, you would use
this:
➢
This starts at 5, decreases by one till 0 is
reached.
➢
Remember the last number is not used.
To end at 1 you have to use 0, to end at 0 you
➢
have to use -1
24
The For Loop: Specifying Descending
Values
➢
The output will look like this:-
25
The For Loop: Putting It All Together
➢
Now let's put some of these ideas together and
write a program that gets some numbers from
the user and computes the average.
The program needs to be flexible enough to
➢
26
The For Loop: Putting It All Together
➢
Once you know that value, you can set up the
for loop to run that many times.
➢
Each time through the loop, you ask the user for
a value and add it to an accumulator variable.
That’s a variable that holds the sum of all the
➢
numbers entered.
➢
Once the user enters the appropriate number of
values, the program stops looping, computes the
average, and displays the result.
27
The For Loop: Putting It All Together
➢
Here’s how the code could look like:-
28
The For Loop: Putting It All Together
➢
Here’s how the code could look like:-
30
Python Looping Extras: Nesting Loops
and Compound Conditions
➢
Python gives you all the same extras for loops as
other languages, plus more.
➢
Here’s a quick tour of some of the most useful
and interesting extras.
31
Python Looping Extras: Nesting Loops
➢
Nesting loops is the same idea as nesting if
statements.
➢
You simply place one loop inside another.
And you're free to do this as many times as you
➢
want.
➢
The key is to watch your indenting in Python
because this is what determines the statements
that are inside each loop.
32
Python Looping Extras: Nesting Loops
➢
For example if you want to print the
multiplication table from 0 to 12 you can use
this.
33
Python Looping Extras: Compound
Conditions
➢
Python also gives you the ability to write compound
conditions with your while statements.
➢
Be careful when you do this, though. Just like with
compound conditions in if statements, sometimes you can
accidentally create these conditions incorrectly, but
Python will still attempt to run them. Take a look at the
following example:
while answer == 'y' or 'Y':
➢
This will always evaluate to true - in the second part of
the compound statement, 'Y' evaluates to the Boolean
value true.
So use:
➢
➢
Like many programming
languages, Python
provides a break
statement.
➢
By placing the word break
inside your loop, you force
the program to stop at that
exact point and exit the
loop.
➢
The program will then
continue with the first
statement following the
loop.
35
Python Looping Extras: The break
Statement
➢
For example:
➢
What will these codes output?
36
Python Looping Extras: The continue
Statement
➢
The continue statement
enables you to skip the
remaining statements in
your loop and start a new
one.
➢
Or to put it differently
continue is used to skip
the current block, and
return to the "for" or
"while" statement.
37
Python Looping Extras: The continue
Statement
➢
Here are some examples:
38
Python Looping Extras: The continue
Statement
➢
Here are some examples:
39
Python Looping Extras: The else Clause
➢
Unlike most other languages Python gives you the option
to use the else clause with your loops.
With “if” statements following else were executed if the
➢
you’re running the else clause only when the loop exits
normally.
➢
In this case, “exits normally” means that it completed
executing by going through all items in the for loop or that
the Boolean condition of the while statement finally
evaluated to false.
➢
On the other hand, if a loop exits because it encounters
the break statement, then it wasn't a normal exit.
40
Python Looping Extras: The else Clause
➢
Here how the program flow will look like with
and with out else.
41
Python Looping Extras: The else Clause
➢
Example of else clause with a for loop:-
42
Python Looping Extras: The else Clause
➢
But when will you actually use this in a program?
➢
One example would be this.
➢
Imagine you want to create a program with a
search component. When users get to a value
they're searching for, you want the program to
stop searching and do something else. Maybe
you want to ask the user for a phrase and a
letter. You then want your program to determine
if that letter is somewhere in the phrase and
report this to the user.
43
Python Looping Extras: The else Clause
➢
This is a great example of using an else clause. Now if the
program finds the specified letter, we'll execute the break
statement, leading to an exit that isn't normal. This means that
the last message saying that the letter wasn't found won't print.
44
Python Looping Extras: The else Clause
➢
When you run it – you will see something like
this:
45
Temprature Converter
➢
Here’s a program that converts between C and F.
Try to modify it so that it will prompt the user if
he wants to continue or exit. If the user chooses
to continue it will ask for temperature type.
46
Currency Converter
➢
Try to write a program that converts between
Birr, Dollar and RMB. But this type make it to loop
till the user exits it by typing q or Q.
Use this conversion rates: (or the current rates.)
➢
1 USD= 53 Birr
1 RMB= 8 Birr
1 USD = 6.625
47
Pattern
➢
Write a program that displays this pattern.
48
Patern solution
➢
Here’s the code:
49
Pattern
➢
Now try to do this:
50
Patern solution
➢
One way to do it will be like this:
51
Reverse a string
➢
Write a program in Python to reverse a word.
➢
Ask the user for a word and then print it
reversed.
52
Reverse a string:
➢
A possible solution
53
Lesson 4 Review
➢
This lesson was all about repeating your code. While many
times the use of a loop is merely to make your life as a
programmer easier, there are also many times when the
only way you make your program function properly is to
use a loop.
You learned about the while and for loops in Python.
➢
➢
You saw how the while statement is very similar to the if
statement. However, the while structure will let you
execute a statement as many times as necessary, until
your condition becomes false.
➢
You also learned about the for loop. For the most part, this
is the same idea as the while loop, except that it's kind of a
shorthand version. Additionally, it creates a list of values.
54
Lesson 4 Review
keywords, which give you a lot more control over the execution of
your Python loops.
➢
You also learned about how Python gives you the option of creating
an else clause for your loops. This ability isn't possible in other
languages.
When you really break it down, there are only three control
➢
55
Some exercises:
➢
Write a program in Python to display the
Factorial of a number.
➢
Write a program in Python to reverse a word.
➢
Modify the tax calculator program you’ve
written to ask the user if they want to continue
and if so calculate it till the user inputs Q.
56