Topic 4 Iterations Updated
Topic 4 Iterations Updated
Iteration
What is iteration?
• Repeated execution of a set of statements is
called iteration.
while
<test_condition>:
<Body of while>
indentation
<Body of while>
= < >
< > !=
= = =
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
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:
Start= 0 by default
Step size = 1 by default, where it increments by 1
For loop using range()
Function
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
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.
• 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