0% found this document useful (0 votes)
1 views

Topic 4 Iterations Updated

Uploaded by

h6n5pgjdby
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Topic 4 Iterations Updated

Uploaded by

h6n5pgjdby
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Topic 4 -

Iteration
What is iteration?
• Repeated execution of a set of statements is
called iteration.

• Python provides several language features to make


iteration easier.

• There are two types of iteration:


▪ Definite iteration, in which the number of repetitions
is specified explicitly in advance
Example: for loop
▪ Indefinite iteration, in which the code block
executes until some condition is met
Example: while loop
While Loop
The while loop
• The while loop statement allows you to
repeatedly execute a block of statements as
long as a condition is true.
Syntax of while Loop
• Syntax of while Loop

while

<test_condition>:

<Body of while>
indentation

Test the condition again


While loop
• In while loop,
▪ test expression is checked first.
▪ The body of the loop is entered only, if
the <test_condition> evaluates to True.
▪ After one iteration, the <test_condition> is checked
again.
▪ This process continues until
the <test_condition> evaluate to False.
• Body starts with indentation and the first unindented
line marks the end.
while <test_condition>:

<Body of while>

• the <test_condition> is a Boolean expression.


True False
Use the comparison operators
Use the logical operators.
Compariso
n
operators

= < >
< > !=
= = =
while <test_condition>:

<Body of while>
• Python interprets any non-zero number for the
<test_condition> as True. None and 0 are interpreted
as False.
The while loop (Examples)
• while loop to print numbers from 1 to 5.
Pattern to follow in While
Loop A is Iterator
The while loop (Examples)
• Here is a simple program that counts down from 5
until 1.
The while loop (Examples)
Program to find sum of numbers from 1 to 10:
(1+2+3+4+5+6+7+8+9+10)

1
• Exercises

• Using while loop, write a Program to Calculate and


print the Average of 5 Numbers given by the user.
average = sum of five numbers/5

• Write a loop to find and print the factorial of any


number

5! = 5 × 4 × 3 × 2 × 1 = 120
Exercise
• Write a Program to Calculate the Average of N
Numbers, where N is a number given by the user,
based on N ask the user to enter the numbers and
calculate the average value. Were the average =
sum of numbers/N
Exercise
While loop and
conditionals
Exercise
• Write python program that accept the final mark for
programming course for 4 students. If the student
score is higher than 50, print( you passed ).
Otherwise print (you Failed ).
Exercise
• Write python program that display the price of
products after discount. The program accepts 3
products price purchased by the user.
• If the product price is higher than 50 OMR, the
discount percentage is 40%. Otherwise, the discount
percentage is 20%. Calculate the discount price for
each product.
Discounted price = product price –(product price * discount
percentage )
Infinite loop
Infinite loops
• An infinite loop repeats the statements without stop.
• This loop is obviously an infinite loop because the
logical expression on the while statement is simply
the logical constant True:

• One of the simplest ways to stop an infinite loop in Python is by using


a keyboard interrupt.
• This method involves pressing the “Ctrl + C” keys on your keyboard
while the program is running.
Infinite loops (Example)
For Loop
The for loop
• When we have a list of things to loop through, we
can construct a definite loop using a for statement.
• Syntax of for Loop
for val in sequence: ✔ Range
<Body of for> ✔ List

• val is the variable that takes the value of the item


inside the sequence on each iteration.
• Loop continues until we reach the last item in the
sequence.
• The body of for loop is separated from the rest of the
code using indentation.
Flowchart of for Loop
For loop using range()
Function
• To loop through a set of code a specified number of
times, we can use the range() function.
• The range() function returns a sequence of numbers.

• Syntax for range() function:-


range(end)
range(start, end)
range(start, end, step size)

Start= 0 by default
Step size = 1 by default, where it increments by 1
For loop using range()
Function

• the last value will be always (end -1)


range(6) 0 1 2 3 4 5

start end-1
range(1,6) 1 2 3 4 5

range(1,10,2) 1 3 5 7 9

Step size
range(5) will generate numbers from 0 to 4
0 1 2 3 4

range(2, 6) will generate numbers : 2, 3, 4, 5


2 3 4 5

range(10, 1, -2) will generate numbers : 1, 3, 5, 7, 9


10 8 6 4 2

range(5,0,-1) will generate numbers : 5, 4, 3, 2, 1


5 4 3 2 1
Exercise
• What is the output of the following code.

Output:
10 7 4 1
end
for loop (examples)
• Print numbers from 0 to • Print numbers from 3 to
4 6
for loop (examples)
• Print numbers from 5 to • Print numbers from 10
1 to 50 and increment by
10
Exercise
• Print the values from 1 to 10 using range function.
Exercise
• What is the output of the following code.

Output:
2 4 6 8
Sum is 20
Loop with
conditions
Loop with conditions
• Loops can have conditional checks inside its body,
ie. the body of loop can have a if or if else or if elif
conditions
• Example: Program to print numbers ending with 5
between 1 to 50
Exercise
• Write a program that finds the numbers that are
divisible by 137(Remainder of division is zero). in the
range 1 to 1000.

✔ How to find if a number is divisible by 137?


✔ Number%137==0
✔ What is the range ?
✔ Range(1,1000)
Break statement
break statement
• break statement is used to jump out of the
loop or terminate the loop.
• i.e. stop the execution of a looping
statement, even if the loop condition has not
become False (while loop) or the sequence of
items has not been completely iterated
over(for loop).
Flowchart of break
break example
• For example, suppose you want to take input from the user
until they type done. You could write:
• The loop condition is True, which is always true, so the loop
runs repeatedly until it hits the break statement.
break example
• Print numbers from 5 to 1 but terminate if
you reach 2
continue statement
The continue Statement
• The continue statement is used to tell Python to
skip the rest of the statements in the current loop
block and to continue to the next iteration of the
loop.

• That is, the current iteration of the loop will be


disrupted, but the program will return to the top of the
loop for next iteration.
Flowchart of continue
continue statement - examples
• Print numbers from 0 to 4 except 2
break and continue
Exercise
• What is the output of the following code.
Exercise
• What is the output of the following code.
Nested loop
Nested Loop
• A nested loop is a loop that occurs within another
loop, structurally similar to nested if statements.
• A loop inside another loop is called nested loop.
• Nested loop can be created using while loop or for
loop

• Syntax:
for [1st iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [2nd iterating variable] in [nested loop]: # Nested
loop [do something]
Nested loop example
• Print the pattern using nested loop
Nested loop
example
Nested loop example
Solution
Nested loop example
Solution

You might also like