Professional Documents
Culture Documents
FALL WIN SEM (2023-24) CSE0106 ETH AP2023243000534 Reference Material I 02-Nov-2023 Module3
FALL WIN SEM (2023-24) CSE0106 ETH AP2023243000534 Reference Material I 02-Nov-2023 Module3
• range function
• loops: for loop, while loop
• Nested loos
• loop control statements: break, continue, pass
• loops with else
range function
We can generate a sequence of numbers using range() function.
We can also define the start, stop and step size as
range(start, stop, step_size).
• print(list(range(10))) ;
Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
• print(list(range(2, 8)));
Output:[2, 3, 4, 5, 6, 7]
for x in range(6):
print(x)
Output:
Loops in Python
• Loops are used to repeat a set of statements/single statement, a certain number of
times.
• In Python, there are two loops,
1. for loop
2. while loop.
• The Python for loop also works as an iterator to iterate over items in list/dictionary or
characters in strings.
6
for loop
for Loop: It can be used to iterate over a list/string/dictionary or iterate over a range of
numbers.
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string)
Syntax:
for variable in range(starting number , ending number + 1 , step size):
statements
(or)
for element in sequence:
statements
Looking at in...
• 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
9
for loop
• In Python a for-loop is used to step through a sequence
e.g., count through a series of numbers or step through the lines in a file.
• Syntax:
for <name of loop control> in <something that can be
iterated>:
body
for loop
• Syntax:
body
#1. Program to find the sum of numbers in list=[1,2,3]
slide 12
#1. Program to find the sum of numbers in list=[1,4,1]
total = 0
for i in range(1, 4, 1):
total = total + i
print("i=", i, "total=",total)
print("Done!")
slide 13
#1. Program to find the sum of numbers in list=[1,4,1]
1) Initialize control
2) Check condition
total = 0
for i in range(1, 4, 1): 3) Execute body
total = total + i
4) Update control print("i=", i, "total=",total)
print("Done!")
for Loop example
# 2.Program to find the sum of all numbers stored in a list
15
for Loop example
# 2.Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
16
Example of for loop
• Output:
Counting in a Loop
count = 0
print('Before', count)
for i in [9, 41, 12, 3, 74, 15] :
count = count + 1
print(count, i)
print('After', count)
4. Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output:
4. Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output:
Counting in a Loop
count = 0
print('Before', count)
for i in [9, 41, 12, 3, 74, 15] :
count = count + 1
print(count, i)
print('After', count)
Counting in a Loop
Output:
count = 0 Before 0
print('Before', count) 19
for i in [9, 41, 12, 3, 74, 15] : 2 41
count = count + 1 3 12
print(count, i) 43
print('After', count) 5 74
6 15
After 6
Note : To count how many times we execute a loop we introduce a counter variable that starts at
0 and we add one to it each time through the loop.
Finding the Average using a Loop
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15] :
count = count + 1
sum = sum + value
print(count, sum)
print('After', sum, sum/count)
Finding the Average using a Loop
count = 0 Output
sum = 0 Before 0 0
print('Before', count, sum) 19
for value in [9, 41, 12, 3, 74, 15] : 2 50
count = count + 1 3 62
sum = sum + value 4 65
print(count, sum) 5 139
print('After', sum, sum/count) 6 154
After 154 25
Note : An average just combines the counting and sum patterns and divides when the
loop is done.
Definite Loops
• Quite often we have a list of items of the lines in a file - effectively a finite set
of things.
• We can write a loop to run the loop once for each of the items in a set using
the Python for construct.
• These loops are called "definite loops" because they execute an exact number
of times.
• While loops are called "indefinite loops" because they keep going until a logical
condition becomes False
• The loops we have seen so far are pretty easy to examine to see if they will
terminate or if they will be "infinite loops“
While Loop: This is used, whenever a set of statements should be repeated based on a
condition.
• The control comes out of the loop when the condition is false.
• In while loop we must explicitly increment/decrement the loop variable (if any) whereas in
for, the range function would automatically increment the loop variable.
Syntax:
while condition:
statement(s)
increment/decrement
29
While loop
Syntax: • Example
i=1
while condition: while i < 6:
print(i)
statement(s)
i += 1
increment/decrement
Output
30
While loop
Syntax: • Example
i=1
while condition: while i < 6:
print(i)
statement(s)
i += 1
increment/decrement
Output
31
Example of While loop(cont…)
𝑖=1
While 𝑖 < = 5 :
print (“𝑖 = ”, 𝑖)
𝑖 += 1
Print(“Done!”)
Example of While loop(cont…)
Output:
𝑖=1
While 𝑖 < = 5 :
print (“𝑖 = ”, 𝑖)
𝑖 += 1
Print(“Done!”)
Example of While loop(cont…)
Output:
Flowchart of while loop
35
Example:
Flow chart of the Problem
Planning the while Loop
Balance=10000
Target=20000
year=0
while Balance<Target:
Interst=Balance*0.05
Balance=Balance+Interst
year=year+1
print(year," year","Balance",Balance)
print("Balance=",Balance)
Planning the while Loop
Balance=10000
Target=20000
year=0
while Balance<Target:
Interst=Balance*0.05
Balance=Balance+Interst
year=year+1
print(year," year","Balance",Balance)
print("Balance=",Balance)
Planning the while Loop
Balance=10000
Target=20000
year=0
while Balance<Target:
Interst=Balance*0.05
Balance=Balance+Interst
year=year+1
print( year," year","Balance",int(Balance))
print("Balance=",int(Balance))
Planning the while Loop
Balance=10000
Target=20000
year=0
while Balance<Target:
Interst=Balance*0.05
Balance=Balance+Interst
year=year+1
print( year," year","Balance",int(Balance))
print("Balance=",int(Balance))
n=1739
total=0
while n>0:
digit=n %10
total=total+digit
n=n//10
print("total", total)
Output:
Calculate the sum of digits of a given number
n=1739
total=0
while n>0:
digit=n %10
total=total+digit
n=n//10
print("total", total)
Output: total 20
Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
1) break
2) continue
3) pass
Control Statement and Description
break statement: Terminates the loop statement and transfers execution to the statement
immediately following the loop.
Control Statement and Description
break statement: Terminates the loop statement and transfers execution to the statement
immediately following the loop.
continue statement: Causes the loop to skip the rest of its body and immediately retest its
condition prior to reiterating.
Control Statement and Description
break statement: Terminates the loop statement and transfers execution to the statement
immediately following the loop.
continue statement: Causes the loop to skip the rest of its body and immediately retest its
condition prior to reiterating.
pass statement : The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
Break and Continue Statement
break statement: This statement is used to terminate the loop it is present in. Control goes
outside the loop it is present in.
• The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
• If the break statement is inside a nested loop (loop inside another loop), the break
statement will terminate the innermost loop.
48
Syntax of break statement
while condition:
statements
if condition:
break
statements
Flow chart for break statement
50
Flow chart for break statement
51
Example of Break statement
56
Example3 of break statement
#Using of break statement inside the loop
57
Continue Statement
• The loop will not be terminated, it just won’t execute the statements below the
continue statement.
Syntax:
while condition:
statement(s)
if condition:
continue
statements
Flow chart of continue Statement
60
Flow chart of continue Statement
61
Example of continue statements
• In Python, break and continue statements can alter the flow of a normal loop.
• Loops iterate over a block of code until the test expression is false, but
sometimes we wish to terminate the current iteration or even the whole loop
without checking test expression.
64
Pass Statement
Pass statement: This statement is used as placeholder.
For example, we want to create a function but are not sure of its content. If
we create a function and leave it, an error will occur. To counter this error,
we use pass statement.
• Example
• The pass statement is useful when you don’t write the implementation
of a function but you want to implement it in the future.
• So, to avoid compilation errors, you can use the pass statement.
67
for loop with else
• In most of the programming languages (C/C++, Java, etc), the use of else statement
has been restricted with the if conditional statements.
• But Python allows us to use the else condition with for loop also.
• The else block just after for/while is executed only when the loop is NOT terminated
by a break statement.
68
for loop with else
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
69
for loop with else
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
Output
1
2
3
No Break
70
While loop with else
i=1
while i < 6:
print(i)
i =i+2
else:
print("i is no longer less than 6")
71
While loop with else
i=1
while i < 6:
print(i)
i =i+2
else:
print("i is no longer less than 6")
72
Nested Loops
One loop executes inside of another loop(s).
Example structure:
Outer loop (runs n times)
Inner loop (runs m times)
Body of inner loop (runs n x m times)
Nested loops
• Example
74
Example of Nested for loop
Input : 4
Output:
1
12
123
1234
75
Example of Nested for loop
n=int(input()) Output:
for i in range(1,n+1): 1
for j in range(1,i+1):
print(j, end=' ') 12
print('') 123
1234
76
Nested While Loop
• The body of while loop consists of statements. And these statements could be another
while loop, if statement, if-else statement or for loop statement or by that nature any
of such.
• In the following example, we will write a while loop statement inside another while
loop. Its like while in while which is nested while loop.
Print pattern by using Nested while loop
Output:
*
**
***
****
*****
******
*******
********
*********
**********
Print pattern by using Nested while loop
Output:
*
i=1 **
while i < 11:
j=0 ***
while j < i: ****
print('*',end=‘’) *****
j=j+1
print() ******
i=i+1 *******
********
*********
**********
Practice Problems
1. Find the maximum number from the given three numbers.
2. Write a program to print the squares of 1,2,...,10 with for loop.
3. Write a program to print the squares of 1,2,...,10 with while loop.
4. Find n! for given n
5. Find the sum of first n integers for given n
6. Write a Python program to find those numbers which are divisible by 7 and multiple of 5,
between 1 and 100 (both included).
7. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
9) A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
10) Print multiplication table of n using loop for given number n.
11) Write a for loop that writes out the decimal equivalent of the reciprocals 1/2, 1/3,1/4, ... ,
1/19, 1/20.
8) Write program to print output as following
1
1 1
1 1 1
1 1 1 1
9) Write a for loop that writes out the decimal equivalent of the series 1/2+1/3+1/4+ ...+1/19+1/20.
10) Given two input number A and B. Find the sum of number between A and B. For example:
input: A=2, B=5 output:14 (2+3+4+5)
11) Print the following pattern as a output:
*********
*0*0*0*0*
*********
*0*0*0*0*
*********
12) Write a Python program that prompts user to enter numbers. The process will repeat until user
enters 0. Finally, the program prints sum of the numbers entered by the user.
16) Print the factors of given number.
18) Write a program to find greatest common divisor (GCD) or highest common factor (HCF) of given
two numbers.
19) Take 10 integers from keyboard using loop and print their average value on the screen.
20) Write a program to print all the numbers from 1 to 1000 that are not divisible by 2, 3, 5, 7, 11, 13, 17
and 19.