Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Lesson 4 Looping

Lesson 4 of the Python programming course focuses on looping structures, specifically the while and for loops, which allow for repeated execution of code blocks based on conditions or specified iterations. The lesson covers the syntax and functionality of these loops, including handling infinite loops, nesting loops, and using control statements like break and continue. Additionally, it provides practical examples and exercises to reinforce the concepts learned.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lesson 4 Looping

Lesson 4 of the Python programming course focuses on looping structures, specifically the while and for loops, which allow for repeated execution of code blocks based on conditions or specified iterations. The lesson covers the syntax and functionality of these loops, including handling infinite loops, nesting loops, and using control statements like break and continue. Additionally, it provides practical examples and exercises to reinforce the concepts learned.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 56

Lesson 4: Looping (and Looping and

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

Then there are other times when there's just no


way to handle a specific task without a loop.



For example, what if instead of forcing your
users to enter 10 numbers to be averaged, you
let them enter as many numbers as they want?

Or how about letting users launch your program
once and then run it over and over until they
decide to quit?

For example what about if you wanted the
temperature or currency converter to run until
the user decides to stop?
5
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

guess what this number will be at design time.


But with loops, you'll be able to handle the situation.


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

Imagine the simple example of printing the


numbers 1 through 5. How would you do that?


What about it was 10000 times? Or you want the

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

But what is happening here?



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

5, it enters the loop body.



The program prints the value of
the number variable, this time 1,
and then increment number.

10
The while Loop: The Basics of the While
Loop

This process continues until


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

of reverse, but “counter” in the sense of using a counting mechanism).



For example, maybe you want to print a number and then ask users if
they want to see the next higher number. Here’s an example:

13
The while Loop: Conditional Loops


The output should look
something like this:-

14
The while Loop: Examples

Write a program that counts down from 100 to 1.


Modify it to countdown from a user input n to 1.



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

updating your counting variable.


The update occurs inside the for statement.

Another difference is that the Boolean condition isn't explicitly


written in the for statement the way it is in a while statement.


The syntax is :-

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

To use the range function,


you'll need two numbers:



the starting value and the ending
value.

It's important to remember
that the range function, like
the slicing strings in other
programs, does not use the
last number you provide.

This means that if you want
the numbers between 1 and
5, you'll use the following
range: range(1,6)
18
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

and stores it in the number variable.


Next, control enters the body of the for loop and the print statement is

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

which you can find by typing help(range) at the


prompt.

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

handle any number of numbers.



While it may seem that a while loop is
appropriate here, it can be done with a for loop
just as easily.
First, you’ll prompt the user for the number of

numbers that they want to average.

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

It's interesting to note in the above example that


even though Python creates a list of numbers from


0 to (num_of_nums - 1), the program never really
uses any of these values.
Instead, it just uses the fact that there are

num_of_nums values in the list, which controls the


number of times it loops.

You can use
for count in range (num_of_nums, 0, -1):

And the program will just work the same.

Now try to do that with the while loop.
29
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:

while answer == 'y' or answer == 'Y':


34
Python Looping Extras: The break
Statement


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

condition was false.


The same sort of idea happens here except that now

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:-

After trying the above code – replace continue


with break and see if there’s anything different.

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

The code will look like this:-



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

The lesson finished up with a discussion of the break and continue


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

structures that any programming language uses: sequence,


decisions, and loops.

In the next lesson, you’ll explore some more functions. You've used
two already: input and range. Functions are useful because they
enable you to organize and make your code more modular. That is,
you can write a group of code to do some calculation once and then
reuse this code in a variety of other places in your program without
typing it in again. Instead, you simply call on the function to run.

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

You might also like