You are on page 1of 49

Click icon to add picture

CONTROL -7
(REPETITION)
Basimah Aljhne
1. Different Python Loops Click icon to add picture
2. Python While Loop
3. Python For Loop
4. Loop Control Statements in Python
5. Exercise
Click icon to add picture
Different Python Loops
1. Why to use loops
2. What are loops
3. Types of loops in Python
Why to use loops

100 Times
IF I ask you to Create program that
 aske the user their name
 and print their name with HI

Manual Loop

100 Times

100 Times
Why to use loops

 Loop can be defined as one of the basic logical structures of computer


programming

 Defining loops in codes allows computers to perform particular tasks


repeatedly.

 Computer programming languages require loops, so that the codes


execute the actions as many times as needed.
What are loops
 Loop allows the execution of a statement or a group of statements multiple times.
 In order to enter the loop there are certain condition defined in the beginning
 Once the condition become false the loop stops and the control moves out of the
loop.
Types of loops in Python

1 2

While loop for loop

Loop Control
Statements
Click icon to add picture
Python While Loop While loop
1. Basic While loops
2. An Infinite Loop
Basic While loops
A While loop works as follow:
• While loops are known as indefinite or conditional loops.
• They will keep iterating until certain condition are met.
• There is no guarantee ahead of time regarding how many times the loop will iterate
Basic While loops
A While loop works as follow:
1-The program enter the While construct and evaluates the Boolean
expression (condition).
2-If the Boolean expression is True, then the associated While suite is
executed.
3- At the end of the suite, control flow back to the top of the While
where the Boolean expression is re-evaluated.

4- if the Boolean expression yield True, the loop executes again.


If the Boolean expression yield False, then the While suite is skipped
and the code following the while loop is executed .

syntax

while boolean expression:


suite
Basic While loops
Write a program that print out the numbers zero through nine:

#Initialization (loop -control variable)

#test loop-control variable at beginning of loop

#change the loop-control variable


Basic While loops

 Outside the loop, initialize the loop -control variable

 Somewhere inside the loop you perform some operation which changes the state of
the program, eventually leading to a False boolean and exiting the loop.

 Some thing to note about a while work.


 The condition is evaluated before the suite is executed.
 This mean that if the condition start out False, the loop will never run.
 If the condition always remained True, the loop will never end.
115
115>112 is true, do loop
Print 115
114 115-1
114>112 is true, do loop
115 Print 114
114 113 114-1
113
113>112 is true, do loop
The tea is cool enough
Print 113
3 times we enter the loop 112 113-1
112>112 is false , skip loop
Print the tea is cool enough
Test yourself: Following the code. Figure out what is printed. :

4
6
8

6
8
10
Test yourself: Following the code. Figure out what is printed. :

Here’s an example of a loop that is not able to finish its


execution →
This loop will infinitely print “I’m stuck inside a loop” on the
screen.
Q1:Write program the take number from the user and return the sum of sum = 1+2+3+...+n

1) Read number from the user

2) initialize the loop -control variable


What is the value?

Answer: 3) Do I need another variable ?

Q2: Write a python program to find


4) Loop body:
the factorial of a number entered by What is the condition [start , end]
user. Do not forget to change the loop-control
Factorial=1*2*3 *n
first_int 20
15

What is the output of the following code? second_int 15


10
why
ten_count 1

loop_count 1

20 10 True
True

(a) Given user input of 20 followed by an input of 10


(b) Given user input of 20 followed by an input of 20
first_int 10
15

What is the output of the following code? second_int 20


15

ten_count 1

loop_count 12

15 15 True
False

(a) Given user input of 20 followed by an input of 10


first_int 10

second_int 20
What is the output of the following code?
ten_count 1

loop_count 2

10 20 False

(a) Given user input of 20 followed by an input of 20


Answer (a)Given user input of 20 followed by an input of 10

(b)Given user input of 20 followed by an input of 20


An Infinite Loop
 if you forget to increment the counter variable in python, or write flawed logic, the
condition may never become false.

 In such a case, the loop will run infinitely, and the conditions after the loop will
starve. To stop execution, press Ctrl+C.

i=9
Loop never starts while i>11:
print(i)

i=9
Loop never ends while i<11:
print(i)
Exercise

 Write a python program which reads 20 numbers from user and computes their
average.

1) initialize the loop -control variable


What is the value?

2) Do I need another variable ?

3) Loop body:
What is the condition [start , end]
Do not forget to change the loop-control
What is the statements that need to be repeat
:Answer
Click iconfor
toloop
add picture
Python For Loop
1. The range() function
2. Iterating on lists or similar constructs
3. Iterating on indices of a list or a
similar construct
4. Equivalence of while and for
Basic For for iterating_var in sequence:
#suite
letter pyt
for letter in ‘python’:
print (“letter :”,letter)
Output

fruits = ['banana', 'apple', 'mango’]


for fruit in fruits:
print 'Current fruit :', fruit

A python for loop iterates through each value in a sequence.


Basic For

 Python for loop can iterate over a sequence of items.


 In Python, we use the ‘in’ keyword.
for letter in ‘python’:
print (letter)

•The iteration variable “iterates” though the sequence


(ordered set)

•The block (body) of code is executed once for each value


in the sequence

•The iteration variable moves through all of the values in


the sequence
Do it
[5, 4, 3, 2, 1]
Yes No Move i ahead
Done? 5
4
for i in [5, 4, 3, 2, 1] :
3
print i print i
2
print 'Blastoff!'
1
Blastoff!

print 'Blast off!'


Definite loops (for loops) have explicit iteration
variables that change each time through a loop. These
iteration variables move through the sequence or set.
The range() function

 This function yields a sequence of numbers. When called with one argument, say n, it
creates a sequence of numbers from 0 to n-1.

1
for num in range(1,5): [1, 2, 3, 4] 2
print(num) 3
• range represents the sequence 1, 2, 3, 4 4
• for loop assigns num to each of the values in the sequence, one at a time, in
sequence
• prints each number (one number per line)
Range function and for loop
The range function has two more versions.  range(a,b,k) k is the step value.
 range (a,b)

 range(a)
Iterating on lists or similar constructs

 You aren’t bound to use the range() function.


 You can use the loop to iterate on a list or a similar construct.

1
2
3
 You can also iterate on a string.
w
i
s
d
o
m
for iterating_var in sequence:
#suite

range(a)
list range(a,b)
string range()
range(a,b,k)
Equivalence of while and for
It is possible to write a while loop that behaves exactly like for loop.
However, not every while loop can be expressed as a for loop.

Consider the simple for loop which print the sequence rang from 0 to 4

We can write an equivalent while loop as:

The for loop is easier to read and understand, but it is useful only for moving through the elements of objects with
iterators.
Test yourself: :

1-Prints out the numbers from 1 to 10 4-Loop through and print out all even numbers from the
numbers list in the same order they are received
for x in range(1,11): number=[1,2,3,4,5,6,7,8,9,10,11]
print(x)
number=[1,2,3,4,5,6,7,8,9,10,11]
2- Prints out the numbers 3,4,5 for n in number:
if n%2==0:
range() list print(n)

for x in range(3, 6): for x in [3,4,6]: 5-Loop through and print out the summation of them
print(x) print(x) number=[1,0,10,4]

3- Prints out the numbers 3,5,7


for x in range(3, 8, 2):
print(x)
(Filtering in a Loop)

We use an if statement in the loop to catch / filter the values we are looking for.

6-(Filtering in a Loop)
Loop through and print out all the value that
larger than 20
number=[9, 41, 12, 3, 74, 15]
Click icon to add picture
Loop Control Statements in Python
1. break statement Loop Control
2. continue statement Statements
Break statement
•A break statement in a loop, if executed, exits the loop.

•It exists immediately, skipping whatever remains of the loop as well as the else
statement (if it exists) of the loop.

b
r
e
a
continue statement

•A continue statement, if executed in a loop, means to immediately jump back to the


top of the loop and re-evaluate the conditional

•Any remaining parts of the loop are skipped for the one iteration when the continue
was executed.

i 1
0 1
T
continue statement

•A continue statement, if executed in a loop, means to immediately jump back to the


top of the loop and re-evaluate the conditional

•Any remaining parts of the loop are skipped for the one iteration when the continue
was executed.

T i 2
1
0 1
2
continue statement

•A continue statement, if executed in a loop, means to immediately jump back to the


top of the loop and re-evaluate the conditional

•Any remaining parts of the loop are skipped for the one iteration when the continue
was executed.
1
T i 5
6
0
2
3
T 4
5
7
8
What is the output of the following code?

If your while loop is controlled by “while True:”, it will


loop forever. How do
you control your loop so that it will stop? Provide a brief
example in Python code.
Summary

while test1:
statement_list_1
if test2: break # Exit loop now; skip else
if test3: continue # Go to top of loop now
# more statements
else:
statement_list_2 # If we didn't hit a 'break’
statement # program
# 'break' or 'continue' lines can appear anywhere
Control
Statement
continue

IF

If else break

If elif else while

for
Read
Exercise

 Write a python program which computes the sum of all the odd numbers
between 0 and 100.
1) For or while

1) Do you need variables?

1) Do you filter?
Exercise

 Write a python program which reads numbers from user and computes their
average. To stop the user he should enter 00

1) For or while

While True:

break
1) initialize the loop -control variable
What is the value?

2) Do I need another variable ?

3) Loop body:
While ()=True +break
• Do not forget to change the loop-control
• What is the statements that need to be repeat
• What is the break condtion

Can not do it with for


Why??
Exercise

 Write a python program which reads unknown number of integers and counts
the number of odd numbers and the count of even numbers. Assume the input
integers are all positive.

1) For or while

2) Do you need variables?

3) Do you filter?
Exercise

 Write a python program which reads unknown number of integers and counts
the number of odd numbers and the count of even numbers. Assume the input
integers are all positive.

You might also like