0% found this document useful (0 votes)
47 views67 pages

Loop

The document discusses loops in Python, including the concepts of repetition in tasks and the use of 'for' and 'while' loops. It explains the range() function, operators 'in' and 'not in', and provides examples of how to use loops with lists, tuples, and strings. Additionally, it includes programming exercises for practicing loop concepts.

Uploaded by

saravagawal4321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
47 views67 pages

Loop

The document discusses loops in Python, including the concepts of repetition in tasks and the use of 'for' and 'while' loops. It explains the range() function, operators 'in' and 'not in', and provides examples of how to use loops with lists, tuples, and strings. Additionally, it includes programming exercises for practicing loop concepts.

Uploaded by

saravagawal4321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 67
for more updates visit: www.python4csip.com Loop — repetition of task ICO VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com What is Loop? e As we have already studied there are many situation where we need to repeat same set of tasks again and again. Like while writing table of any number we multiply same number from | to 10, multiplying number from n to | to find the factorial, In real life, to prepare parathas, suppose to prepare your bag with all items, daily coming to school again and again, etc. Please explore more real life conditions where repetition of task was done by you. for more updates visit: www.python4csip.com Pseudocode Reference start Input number(n) to print table Let count=1 Display n* 1) <5 Add | to count if count==10: A. Stop else: A. Repeat from Step C Stop VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Python Loop Statements e To carry out repetition of statements Python provide 2 loop statements ° Conditional loop (while) ° Counting loop (for) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com range() function e Before we proceed to for loop let us understand range() function which we will use in for loop to repeat the statement to n number of times. e Syntax: ° range(lower_limit, upper_limit) e The range function generate set of values from lower_limit to upper_limit-I for more updates visit: www.python4csip.com range() function e For e.g. e range(1,10) will generate set of values from 1-9 e range(0,7) will generate [0-6] e Default step value will be +1 i.e. e range(1,10) means (1,2,3,4,5,6,7,8,9) for more updates visit: www.python4csip.com range() function e To change the step value we can use third parameter in range() which is step value e For e.g. e range(1,10,2) now this will generate value [1,3,5,7,9] e Step value can be in —ve also to generate set of numbers in reverse order. e range(10,0) will generate number as [10,9,8,7,6,5,4,3,2,1] for more updates visit: www.python4csip.com range() function e To create list from 0 we can use ° range(10) it will generate [0,1,2,3,4,5,6,7,8,9] VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Operators in and not in e The operator in and not in is used in for loop to check whether the value is in the range / list or not e For e.g. >>> 5 in [1,2,3,4,5] True >>> 5 in [1,2,3,4] False for more updates visit: www.python4csip.com >>>’a’ in ‘apple’ True >>>’national’ in ‘international’ True VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Program to check whether any word is a part of sentence or not line = input("Enter any statement") word = input("Enter any word") if word in line: print("Yes ", word, "is a part of ",line) else: print("No", word ," is not part of ",line) for more updates visit: www.python4csip.com for loop efor loop in python is used to create a loop to process items of any sequence like List, Tuple, Dictionary, String e It can also be used to create loop of fixed number of steps like 5 times, 10 times, n times etc using range() function. for more updates visit: www.python4csip.com Example — for loop with List School=["Principal","PGT","TGT","PRT"] for sm in School: print(sm) Example — for loop with Tuple Code=(10,20,30,40,50,60) for cd in Code: print(cd) for more updates visit: www.python4csip.com Let us understand how for loop works Code=(1 0,20,30,40,50,60) for cd in Code: print(cd) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com First it will create Tuple ‘Code’ Code=(1 0,20,30,40,50,60) for cd in Code: print(cd) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com Then for loop starts, it will pick values one by one from Code and assign it to cd Code=(I 0,20,30,40,50,60) for cd in Code: print(cd) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Then for loop starts, it will pick values one by one from Code and assign it to cd VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Then for loop starts, it will pick values one by one from Code and assign it to cd Code=(1 0,20,30,40,50,60) for cd in Code: print(cd) oes for more updates visit: www.python4csip.com Then for loop starts, it will pick values one by one from Code and assign it to cd Code=(! 0,20,30,40,50,60) for cd in Code: print(cd) oes for more updates visit: www.python4csip.com Then for loop starts, it will pick values one by one from Code and assign it to cd | Code=(1 0,20,30,40,50,60) | for cd in Code: print(cd) oes 10 FOR LOOP WILL yl) AUTOMATICALLY ENDS WHEN LAST ITEM OF AND SO ON... LIST IS PROCESSED for more updates visit: www.python4csip.com for loop with string for ch in ‘Plan’: print(ch) The above loop product output P as 9 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR a 7 for more updates visit: www.python4csip.com for with range() Let us create a loop to print all the natural number from | to 100 for i in range(1,101): print(i,end='\t') ** here end=‘\t’ will cause output to appear without changing line and give one tab space between next output. VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com Program to print table of any number - num = int(input("Enter any number ")) » for iin range(,1 1): print(num,'x',i,"=";num*i) Program to find the sum of all number divisible by 7 between | to 100 sum=0 for i in range(1,101): ifi % 7 ==0: sumt+=i print("total of number divisible by 7 between | to 100 is ",sum) for more updates visit: www.python4csip.com Lab work WAP to enter any number and find its factorial WAP to print the following fibonacci series 0, 1, 1,2, 3,5,8,........n terms WAP to enter 10 number and find the sum and average. WAP to enter Lower_Limit, Upper_Limit and find the sum of all odds and evens number between the range separately for more updates visit: www.python4csip.com while loop e While loop in python is conditional loop which repeat the instruction as long as condition remains true. elt is entry-controlled loop i.e. it first check the condition and if it is true then allows to enter in loop. ewhile loop contains various loop elements: initialization, test condition, body of loop and update statement for more updates visit: www.python4csip.com while loop elements |. Initialization : it is used to give starting value in a loop variable from where to start the loop 2. Test condition : it is the condition or last value up to which loop will be executed. 3. Body of loop : it specifies the action/statement to repeat in the loop 4. Update statement : it is the increase or decrease in loop variable to reach the test condition. Dd for more updates visit: www.python4csip.com Example of simple while loop i=d while i<=10: printci) i+=1 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Example of simple while loop i=1 Dd while i<=10: Test condition print(i) it=1 U p d a t Cy VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Let us see the flow of loop Pd i=1 while i<=10: printci) i+=1 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Let us see the flow of loop ist while i<=10: printci) i+=1 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Let us see the flow of loop i=1 while i<=10: print(i) i+=1 lola ele i for more updates visit: www.python4csip.com Let us see the flow of loop — j=1 me while i<=10: evn as Print(i) = i+=1 i for more updates visit: www.python4csip.com Let us see the flow of loop K | I vo while i<=10: unas print(!) = it=1 i for more updates visit: www.python4csip.com Let us see the flow of loop i=1 while i<=10: print(i) i+=1 for more updates visit: www.python4csip.com Let us see the flow of loop — j=1 me while i<=10: evn as Print(i) = i+=1 i 2 for more updates visit: www.python4csip.com Let us see the flow of loop K | I vo while i<=10: unas print(!) = it=1 i 2 for more updates visit: www.python4csip.com Let us see the flow of loop K | I while i<=10: eet vie prinkG) = it=1 for more updates visit: www.python4csip.com Let us see the flow of loop i=1 while i<=10: print(i) In this way loop will execute for the values 4 to 10, let us see from PMT for more updates visit: www.python4csip.com Let us see the flow of loop i=1 while i<=10: print(i) In this way loop will execute for the values 4 to 10, let us see from PMT for more updates visit: www.python4csip.com Let us see the flow of loop ist while i<=10: eet vie print(!) = it=1 for more updates visit: www.python4csip.com Let us see the flow of loop K | xt while i<=10: eet vie prinkG) = it=1 i 2 i} Pr ) 6 7 8 @) for more updates visit: www.python4csip.com Let us see the flow of loop K | I _ while i<=10: evn as Print(i) = i+=1 i 2 i} Pr ) 6 7 8 @) for more updates visit: www.python4csip.com Let us see the flow of loop K | I asl 4 while i<=10: eee evn ue onan it=1 i 2 i} Pr ) 6 7 8 @) for more updates visit: www.python4csip.com Let us see the flow of loop | ist while i<=10: re eet vie prinkG) = it=1 10<=10? i 2 i} Pr ) 6 7 8 @) a ° for more updates visit: www.python4csip.com Let us see the flow of loop K | I _ while i<=10: evn as Print(i) = i+=1 i 2 i} Pr ) 6 7 8 @) a ° OUTPUT i 2 3 Pr ) 6 7 8 @) ie} for more updates visit: www.python4csip.com Let us see the flow of loop i=1 while i<=10: print(i) i+=1 Now the value of i is 11 and condition will return False so loop will terminate for more updates visit: www.python4csip.com Programs of while loop e Convert all ‘for’ loop program with while loop e WAP to enter any number and find its reverse e WAP to enter any number and a digit and count how many times digit is in the number e WAP to enter any number and check it is armstrong or not e WAP to enter any number and check it is palindrome or not e WAP to enter numbers as long as user wishes to enter and find the sum highest and lowest number entered by user for more updates visit: www.python4csip.com WAP to enter any number and find its reverse num = int(input("Enter any number ")) rev=0 num2=num while num>0: rem = num % 10 rev = rev * 10 + rem num //=10 print("Reverse of ",num2," is ",rev) for more updates visit: www.python4csip.com WAP to enter numbers as long as user wishes to enter and find the sum highest and lowest number entered by user choice="y" i=l while choice num 'y": int(input("Enter any number (>0)")) low = num high = num it=1 else: if (high in : while : statement | statement | statement 2 statement 2 else: else: statement(s) statement(s) VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com Example (“else” with while) i=1 while i<=10: Gutpnt print(i) i it=1 5 else: 7 9 print("Loop Over") io Loop Over VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Example (“else” with for) names=["allahabad","lucknow","varanasi","kanpur","agra","ghaziabad" s"mathura","meerut"] city = input("Enter city to search: ") for c in names: if c == city: print(“City Found") break else: print("Not found") Example- program to enter’ "numbers repeatedly and print) their sum. The program ends when the user says no more to enter(normal termination) or program aborts when the number entered is less than zero count = sum = 0 ans ='y' while ans=: num = int(input("Enter number :")) if num < 0: print("You entered number below zero, Aborting...") break sum += num countt=1 ans=input("Continue(y/n)") else: print("You entered ", count, " numbers so far") print("Sum of entered number is :",sum) Example- program to enter "numbers repeatedly and pl print! their sum. The program ends when the user says no more to enter(normal termination) or program aborts when the number entered is less than zero - Enter number :3 Ce To TaD Continue(y/n)y pT) Enter number :6 is Le a core ZL Beueaueyin)y Enter number :50 Enter number :8 Sonth ri Conta Ori ‘ontinue(yin)y You entered 3 numbers so far Pie goumber :-10) Ree You entered number below zero, Aborting... Sum of entered number is : 17 Example- program to input number and tests if it is a prime number or not num = int(input("Enter any number :")) lim = num//2 + | for i in range(2,lim): rem = num % i if rem == 0: print(num," is not a prime number ") break else: print(num," is a prime number ") for more updates visit: www-python4csip.com Example- program to input number and tests if it is a prime number or not - OUTPUT Enter any number :23 23 is a prime number Eran caer for more updates visit: www.python4csip.com Generating Random numbers e Python allows us to generate random number between any range e To generate random number we need to import random library e Syntax: (to generate random number) © random.randint(x,y) ¢ it will generate random number between x to Y ° For e.g.: random.randint(1I,10) ° Refer to code page no. 156 for more updates visit: www.python4csip.com Infinite loop and ‘break’ e We can also execute infinite loop purposely by specifying an expression which always remains True. e However in loop we can mention any condition to exit or terminate loop a=2 while True: print(a) a*¥=2 if a>100: break for more updates visit: www.python4csip.com Nested Loop (loop within loop) e A loop may contain another loop in its body. This form of loop is called nested loop. eln Nested loop, the inner loop will execute for each value of outer loop. e For e.g. if the outer loop is of 4 times and inner loop is of 5 times then statement will execute 4 x 5 = 20 times 7 for more updates visit: www.python4csip.com Syntax of Nested Loop oa for i in sequence: while condition: for j in sequence: while condition: Statement Statement Statement2 Statement2 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO. TEZPUR for more updates visit: www.python4csip.com é Example — to print table of 2 to 10 Pe for i in range (2,11) print ("\nTable of ",i) for j in range(1,11): print (i, 'x',J,! RONORNNNONA Perererrress Vovuvevvves VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Example — Program to print the following patterns KC for i in range (1,6): for j in range(1,itl): print (j,end=' ') i int () for i in range(5,0,-1): for j in range(i,0,-1): print (j,end=' ') print () VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR for more updates visit: www.python4csip.com Write a program to print the following \ pyramid pattern z = 121 i2321, 1234321 space = 5 123454321 for i in range(1,6): print(' '*space,end='') for j in range(1,it1): print (j,end='') for k in range(i-1,0,-1): print (k,end='') print () space-=1 VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWA|, PGT(CS), KV NO.I TEZPUR

You might also like