Problem Solving and Programming in Python Iterative / Looping Statements Vijaya Lakshmi A Ass istant Professor Department of CSE
Session Objectives 2 v 1.2 Learning iterative statements in python
Session Outcomes 3 v 1.2 At the end of this session, participants will be able to – Apply looping statements in Python for solving problems
Agenda 4 v 1.2 Iterative / repeated execution While loop For loop Range Nested Loops Break Continue Pass
Control Flow Control flow — determines order in which statements are executed Three fundamental methods of control flow are: Sequential Statement Conditional Statement Iterative Statement or Repeated Execution 5 v 1.2
Iterative Statement / Repeated Execution 6 v 1.2 To automate the repetitive tasks, iterative statements are used. Iterative statements are decision control statements that are used to repeat the execution of list of statements. Two types of iterative statements. While loop Used when the number of iterations are unknown. Keep on iterating until the condition is false For loop Used when the n o n u t r m l F b l o w e r of i t e r a t D i o e c n e m s b are known. Iterate a predefined number of times
While Loop 7 v 1.2 The while loop is a loop control statement in Python and frequently used in programming for repeated execution of statement(s) in a loop. It executes a sequence of statements repeatedly as long as a condition remains true. The syntax for while loop is given as follows: w h il e t es t − c on d i t i on : # l o o p body s t a t em e n t b l oc k
while statement 8 v 1.2 while statement has header and body while followed by conditional (boolean) expression with colon(:) in the header Returns a value True or False The body should be intended. The loop body will be executed when the condition is True When the condition is false, the loop body will be skipped and the first statement after the while loop will be executed. The condition of the while loop has to be updated after each iteration, if not the condition never becomes false and enters into infinite loop.
While loop Inside the loop some condition decides when to terminate the loop, called as Loop control variable. At each iteration it can be changed by a constant value. The value of loop control variable determines the end of the loop. i , sum , av g = , , . w h il e ( i < 10 ) : sum = sum + i avg= sum / 10 p r i n t ( sum , av g ) 2022 9 v 1.2 9 / 38
While loop - Example1 10 v 1.2 To print numbers from 1 to 5 using while loop count w h il e =0 count < = 5: p r i n t ( ” count= ” , count ) co u nt = co u nt + 1 OUT PUT : \\ c o u nt = c o u nt = 1 c o u nt = 2 c o u nt = 3 c o u nt = 4 c o u nt = 5
While loop - Example2 11 v 1.2 c oun ter zero To find the sum of 10 numbers count= # I n i t i a l i z e the sum = # i n i t i a l i z e sum to w h i l e count < = 1 : #t e s t c o n d i t i o n i f t r u e count= count+ 1 # i n c r eas e the sum = sum + count # add sum + c oun t v alu e o f c oun t by 1 p r i n t ( ”Sum of F i r s t 10 Numbers = ” , sum )
While loop - Example3 the number" )) t h e number " ) ) n u m = i n t ( i npu t ( "E nt er end = i n t ( i npu t ( "E nt er count odd= ev en= c oun t ev en+ 1 odd=count odd+ 1 count even= w h il e ( num < = e n d ) : p r i n t ( " w h il e ") i f ( num% 2 = = 0): c ou n t e l s e : count num=num+1 p r i n t (num) p r i n t ( ” ev en p r i n t ( ” ev en 12 v 1.2 numbe r C s o n ” t , c F l o o w unt eve n D numbers” , count odd ) ) c
While loop - GCD 13 v 1.2 Euclidean algorithm or Euclid’s algorithm G C D of two numbers is the greatest common divisor of two positive integers. A much more efficient method is the Euclidean algorithm. I n p u t : T wo p o s i t i v e i n t eg er s , a and b . The g r ea t es t common d i v i s o r , g , b . Output : of a and I n t er n a l computation : If b!=0 a, b = b, a%b Repeat the above steps
While loop - GCD 14 v 1.2 To compute gcd(48,18) Divide 48 by 18 to get a remainder of 12. Then divide 18 by 12 to get a remainder of 6. Then divide 12 by 6 to get a remainder of 0, which means that 6 is the gcd. Note that we ignored the quotient in each step except to notice when the remainder reached 0, signalling that we had arrived at the answer. Formally the algorithm can be described as:
While loop - GCD 15 v 1.2 Greatest Common Divisor by Using the Euclidian Algorithm m= i n t ( i npu t ( ” g i v e v a l u e f o r a ” ) ) n= i n t ( i npu t ( ” g i v e v a l u e f o r b” ) ) w h i l e n != : m, n = n ,m%n g c d va l = m p r i n t ( ” T he GCD VALUE i s : ” , g c d va l )
For Loop The Python for loop iterates through a sequence of objects, i.e. it iterates through each value in a sequence, where the sequence of object holds multiple items of data stored one after another. The for loop is used to repeat any computations a fixed number of times. The for.... in statement is used to iterate over an ordered collection (sequence) of items Syntax for loop : fo r l o o p 16 v 1.2 c o n t r o l v a r in t s r t l a F l o t w e ments ( D s e ) e sequence :
For Loop When a for loop is used, a range of sequence is specified For loop is executed for each item in the sequence With completion of every iteration the loop control var gets updated with the next item in the sequence After executing for all items in the sequence the flow of control jumps to the immediate statement followed by the for loop 17 v 1.2
For Loop y , z = 1 , 1 fo r i i n [ 1 , 2 , 3 , 4 ] : = y ∗ i = z+ 1 y z p r i n t ( y , z ) O utput 24 5 mb 18 v 1.2
Example 19 v 1.2 f r u i t s = f o r f r u i t p r i n t [ ’ banana ’ , ’ apple ’ , ’ mango ’ ] in f r u i t s : ( ’ C u r r e nt f r u i t : ’ , f r u i t ) Output Current f r u i t : banana Current f r u i t : apple Current f r u i t : mango
20 Range range() is a in- built function used to iterate over a sequence of numbers The general form of the range function is: range( begin, end, step) The ‘begin’ is the first beginning number in the sequence at which the list starts. The ‘end’ is the limit, i.e. the last number in the sequence. The ‘step’ is the difference between each number in the sequence. range( , n) generates sequence { 0,1,...,n- 1 } By default, every number in the range is incremented by 1 but we can specify a different increment using step f o r i in range ( 1 , 5 ) : p r in t ( i , end=” ”) 1 2 3 4 f o r i in range ( 1 , 2 , 2 ) : p r in t ( i , end=” ”) 1 3 5 7 9 11 1 v 3 1.2 15 17 19
For Example- 1 21 v 1.2 To print the square of the numbers: f o r i i n r a ng e ( 1 , 6 ) : sq u a r e= i ∗ i p r in t ( " Square of “ , i ,“ i s : " , square ) To print the even numbers and print the sum sum=0 p r i n t ( ” E ven numbers from t o 10 a r e a s f o r i in range ( , 1 1 , 1 ) : f o l l o w s ” ) i f i % 2= = 0: p r i n t ( i ) sum= sum+ i p r i n t ( ” Sum of E ven numbers from t o 10 i s = ” , sum )
Nested Looping 22 v 1.2 Loops within the loops or when one loop is inserted completely within another loop, then it is called nested loop. num= i n t ( i npu t ( ” en t er t h e number ” ) ) f o r i in range ( 6 ) : p r i n t ( ” i : ” , i ) r a ng e ( i + 1 ) : ( ” j : ” , j , end = ’ ’ ) f o r j i n p r i n t p r i n t ( ) Tr a c i n g FOR LOOP: en t er t h e number 4 i : i : 3 j : j : j : 1 j : 2 j : 3 i : 1 i : 4 j : j : 1 j : j : ec 1 j : 2022 2 j : 38 3 j : 4 i : 2 i : 5 j : j : 1 j : 2 j : j : 1 j : 2 j : 3 j : 4 j : 5
Nested Looping 23 v 1.2 f o r i i n r a ng e ( 5 , − 1 , − 1) : f o r j i n r a ng e ( , i + 1 ) : p r i n t ( i , end = ’ ’ ) p r i n t ( ) Tra c i ng FOR LOOP: loop =1: i =5 , j =(0 , 6 ) p r in t 5 5 5 5 5 5 loop =2: i =4 , j =(0 , 5 ) p r in t 4 4 4 4 4 loop =3: i =3 , j =(0 , 4 ) p r in t 3 3 3 3 loop =4: i =2 , j =(0 , 3 ) p r in t 2 2 2 loop =5: i =1 , j =(0 , 2 ) p r in t 1 1 loop =6: i =0 , j =(0 C , 1 n t ) r p r in t
Example - Pattern 24 v 1.2 f o r i i n r a ng e ( 5 ) : p r i n t ( ) f o r j i n r a ng e ( 5 ) : p r i n t ( ’ ∗ ’ , end = ’ ’ ) Output : ∗∗∗∗∗ ∗∗∗∗∗ ∗∗∗∗∗ ∗∗∗∗∗ ∗∗∗∗∗
Example for list of values in For loop 25 v 1.2 For loop generate sequence explicitly using list of values or implicitly using the range # To f in d f a c t o r s of a number num=int ( input ("e nte r the number : " ) ) print (" the f a c t o r s are ") for i in range ( 1 ,num+1 ): if (num%i ==0): print ( i ) Output : 1 3 5 15
Break The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. Used with for loop and while loop. When compiler encounters a break statement the control passes to the statement that follows the loop in which the break statement appears. 26 v 1.2
Break n= w h i l e n < = 1 : n=n+ 1 i f n = = 5 : b r eak p r i n t ( n ) O utput 1 2 3 4 b er 12, 2022 27 v 1.2 27 / 38
Break - Prime Number 28 v 1.2 num= 23 f o r i i n r a ng e ( 2 , num ) : i f num% i = = 0: p r i n t ( ” c om p osi t e ” ) break e l s e : p r i n t ( ” pr i m e ” )
Continue The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. 29 v 1.2
Continue for val in ” s t r i n g ” : i f val == ” i ” : c o nt i n u e p r i n t ( val , end=’ ’ ’ ’ ) Output s t r n g fo r i i n r ang e ( 1 , 1 1 ) : i f ( i = = 5 ) : c on t i nu e p r i n t ( i , end= ” ” ) Output 1 2 3 4 6 7 8 9 10 er 12, 2022 30 v 1.2 30 / 38
Pass statement Pass is a null statement. Nothing happens when pass is executed. Acts as a place holder fo r l e t t e r i n ” h el l o ” : pass i f ( l e t t e r= = ’ o ’ ) : break p r i n t ( l et t er , end= ” ” ) Output : h e l l 31 v 1.2
Summary 32 v 1.2 Iterative / repeated execution While loop For loop Range Nested Loops Break Continue Pass
Check your understanding 33 v 1.2 Use while loops to solve the following Finding the odd numbers in a given range Exponent of a number. Reversing the given number Counting Number of digits in a given number Write a program to find sum of the digits of the given number Write a program to print the sum of the numbers from 1 to 20 (1 and 20 are included) that are divisible by 5 using the while loop. Check whether a number is palindrome or not. Convert a number to binary. Check a number is Armstrong (sum of cubes of individual digits of a number is same as the number)
Check your understanding 34 v 1.2 Use for loops to solve the following To print the Fibonacci series up to 8. What is the output of the code? for x in ”banana”: print(x) Reversing of a number.
Check your understanding- For loop 1 Sum of the following series: 1 1 − 1 / 2 + 1 / 3 − 1 / 4 + ... 1 /n 2 1 + 1 / 2 2 + 1 / 3 2 + 1 / 4 2 + ... 1 /n 2 1 + 2 2 + 3 2 + 4 2 + ...n 2 Print the following patterns: i ) i i ) i i i ) iv ) ∗ ∗∗∗∗∗ 1 1 ∗∗ ∗∗∗∗ 12 121 ∗∗∗ ∗∗∗ 123 12321 ∗∗∗∗ ∗∗ 1234 1234321 ∗∗∗∗∗ ∗ 12345 3 1 5 / 2 3 8 3454321 35 v 1.2