Mastering Python Loops: A Comprehensive Guide
A Complete Guide to Python Loops, Statements, and Functions
Website Visitors:What is a loop
In computer programming, a loop is a control structure that allows a sequence of instructions to be executed repeatedly until a certain condition is met. Python, being a powerful and easy-to-learn programming language, provides several loop constructs to enable iterative execution of code blocks.
In this article, we will discuss Python loops in detail, including for loops, while loops, and do-while loops. We will also cover the use of break and continue statements, and how to use the enumerate() function to get the index.
Python For Loop
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. The syntax of the for loop is:
|
|
Here, variable
is a temporary variable that takes on the value of each element in the sequence
one by one, and statement(s)
is the code block that is executed each time through the loop.
Example 1: Iterate over a list
|
|
Output:
|
|
Example 2: Iterate over a string
|
|
Output:
|
|
Example 3: Iterate over a range
|
|
Output:
|
|
Example 4: Iterate over custom value
|
|
Output:
|
|
Here, we are running a for loop but at interval of 10. For loop stops if the value is equal to or more than 100.
Example 5: Iterate over a collection
|
|
Output:
|
|
Example 6: Iterate over list in for loop directly
|
|
Output: 25 Above value in for loop is a list. So it goes in that list one by one and prints it. As there is only one value, it will print it and stop.
Python While Loop
The while loop is used to repeatedly execute a block of code as long as a specified condition is true. The syntax of the while loop is:
|
|
Here, condition
is the expression that is evaluated each time the loop is run, and statement(s)
is the code block that is executed as long as the condition
is true.
Example 3: Iterate with a while loop
|
|
Output:
|
|
If you provide one word or one value in a for loop, it will pick each letter and process it. If you want to perform an action on each value, then send it as a list. In below example, when the friends list is passed into the function, it will output as Hi Lisa, and Hi Chris. But when only one value is passed into the function and for loop, it takes that value and processes it letter by letter.
|
|
Output:
|
|
Python Do-While Loop
Python does not have a built-in do-while loop construct like some other programming languages, but we can emulate it using a while loop and a break statement. The basic structure of the do-while loop is:
|
|
Example 4: Implement a do-while loop
|
|
Output:
|
|
Break and Continue Statements
The break
statement is used to exit a loop prematurely, while the continue
statement is used to skip over the current iteration in the loop and move on to the next one. With continue, the current loop (for loop or while loop etc) is stopped where the condition is met and goes to the next value in the loop. The syntax of the break and continue statements is:
|
|
Example 5: Use break and continue statements
|
|
Output:
|
|
In this example, the loop is terminated prematurely when the number
variable equals 5, and any even numbers are skipped over with the continue
statement.
Another example using continue command:
|
|
Output:
|
|
Same example using break command:
|
|
Output:
|
|
When break command is used, when the if statement is true, it immediately breaks the if loop and stops the execution. It will not even process any other commands in the for loop. The print command “Today is sunday” is also not executed when using break command.
When continue command it used, it only stops the execution for the matching value and moves to the next value in for loop. In the example, 7 is the matching value. So 5, 6, are displayed in output, 7 is ignored, next 8 and 9 are displayed on the output along with “Today is sunday” print command.
Using the Enumerate Function
The enumerate()
function is a built-in Python function that can be used to add a counter to an iterable object, such as a list or tuple. The syntax of the enumerate() function is:
|
|
Here, iterable
is the object to be enumerated, and start
is an optional parameter that specifies the starting value of the counter. The enumerate() function returns an iterator that yields pairs of the form (index, element)
.
Example 6: Use the enumerate() function
|
|
Output:
|
|
In this example, the enumerate()
function is used to add an index to each element of the fruits
list, and the resulting pairs are printed out in the loop.
Range function
Range starts from 0 by default. If you want to change it, specify the start value and end value like range(1,5). List of numbers generated in range() are one value less than the end value as range starts from 0.
Range function can receive one, two or three parameters.
-
range(n): 0, 1, 2, … n-1. If it receives one value, it will create a sequence one by one from zero until one less than the value received. Ex: If you’d like to iterate a for loop for x number of times, directly specify the value in range function like range(5). Here, it will start from 0 to 4. You are not looking for a start value here. You just need to loop it for x number of times.
-
range(x,y): x, x+1, x+2, … y-1. If it receives two values, it will create a sequence one by one from the first value until one less than the second value. Ex: If you’d like to iterate a for loop for x number of times but from a starting value you specify, you have to use range(1,5). Here, it will start from 1 to 4.
-
range(p,q,r): p, p+r, p+2r, p+3r, … q-1 (if it’s a valid increment). Finally, if it receives three values, it will create a sequence starting from the first number and moving towards the second number. But this time, the jumps between the numbers will be the size of the third number, and again, it will stop before the second number. Ex: If you’d like to iterate a for loop for x number of times but specific intervals you specify, you should use the range function as range(1,100,10). Here, for loop will iterate at interval of 10.
Use for loop when there is a sequence of items that you want to iterate. For loops are mostly used when there’s a pre-defined sequence or range of numbers to iterate.
Use while loop when you want to repeat an action until a condition changes.
Suggested Article
If you’d like to continue reading, checkout our other python commands article here or browse all other topics here.
Conclusion
Loops are an essential programming construct that allows us to execute a block of code repeatedly until a certain condition is met. Python provides several loop constructs, including for loops, while loops, and do-while loops (which can be emulated using a while loop and a break statement). Additionally, we can use the break and continue statements to control the flow of the loop, and the enumerate() function to add a counter to an iterable object. By mastering these loop constructs and statements, you will be able to write more powerful and efficient Python programs.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.