InterviewSolution
| 1. |
What is the difference between break and continue? |
|
Answer» In order to construct loop, PYTHON language provides two keywords, while and for. The loop formed with while is a conditional loop. The body of loop KEEPS on getting executed till the boolean expression in while statement is true. >>> while expr==True: statement1 statement2 ... ...The ‘for’ loop on the other hand traverses a collection of objects. Body block inside the ‘for’ loop executes for each object in the collection >>> for x in collection: expression1 expression2 ... ...So both types of loops have a pre-decided endpoint. SOMETIMES though, an early termination of looping is sought by abandoning the remaining iterations of loop. In some other cases, it is required to start next round of iteration before ACTUALLY completing entire body block of the loop. Python provides two keywords for these two scenarios. For first, break keyword is used. When ENCOUNTERED inside looping body, program control comes out of the loop, abandoning remaining iterations of current loop. This situation is diagrammatically represented by following flowchart:Use of break in while loop: >>> while expr==True: statement1 if statement2==True: break ... ...Use of break in ‘for’ loop: >>> for x in collection: expression1 if expression2==True: break ... ...On the other hand continue behaves almost opposite to break. Instead of bringing the program flow out of the loop, it is taken to the beginning of loop, although remaining steps in the current iteration are skipped. The flowchart representation of continue is as follows:Use of continue in while loop: >>> while expr==True: statement1 if statement2==True: continue ... ...Use of continue in ‘for’ loop: >>> for x in collection: expression1 if expression2==True: continue ... ...Following code is a simple example of use of both break and continue keywords. It has an infinite loop within which user input is accepted for password. If incorrect password in entered, user is asked to input it again by continue keyword. Correct password terminates infinite loop by break #example.py while True: pw=input('enter password:') if pw!='abcd': continue if pw=='abcd': breakOutput: enter password:11 enter password:asd enter password:abcd |
|