Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration. Following is a simple for loop that traverses over a range , To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in ever.....
Normally the for loop is constructed to iterate over a block for each item in a range. If a premature termination of loop is sought before all iterations are completed, break keyword is used. It is invariably used in a conditional statement inside the body of loop , In this case even though range is upto 20, loop will terminate at x=10
PEP 315 (Python Enhancement Proposal) to include do..while statement has been rejected because it doen't fit in the general format of indented block statement: indented block used by every other Python compound statement. In words of Guido Van Rossum - "Please reject the PEP. More variations along these lines won't make the language more elegant or easier to learn. They'd just s.....
The loop control statement continue abandons the pending statements in current iteration of the looping block and starts next iteration. The continue statement appears in a conditional block inside loop , The output shows that when x is 5 the print statement is not executed and next iteration is undertaken printing from x=6 onwards ,
Python doesn't have an equivalent of do-while loop as in C/C++ or Java. The essence of do-while loop is that the looping condition is verified at the end of looping body. This feature can be emulated by following Python code: , The output is as follows: ,
The else block in a loop (for as well as while) executes after all iterations of loop are completed and before the program flow exits the loop body. The syntax is as follows: , #this will be executed after the program leaves loop body For example: , The output is as shown below: ,
Any loop is formed to execute a certain number of times or until a certain condition is satisfied. However, if the condition doesn't arise, loop keeps repeating infinitely. Such an infinite loop needs to be forcibly stopped by generating keyboard interrupt. Pressing ctrl-C stops execution of infinite loop ,
Sequence objects in Python are an ordered collection of items. Each item in the sequence (list, tuple and string) is accessible by index starting with 0. To traverse elements in a list , To slice one character at a time out of a string ,
Sign up now to get your own personalized profile!
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more