- For loop permit us to iterate over a sequence of values.
let’s examine the below example;
for x in range (5):
- For loops starts with the keyword for with a colon at the top of the road.
- When we look like in function definitions, while loops and if statements, the body of the for loop begins on subsequent line and is indented to the proper.
- But what about those things in between the for keyword and therefore the colon?
- In our example, we’re using the range() function to make a sequence of numbers that our for loop can iterate over.
- During a case like this, our variable x points to the present element within the sequence because the for loop iterates over the sequence of numbers. Keep in mind that in Python and numerous programming languages, a variety of numbers will start at 0, and the list of numbers generated is going to be one but the provided value.
- So range(5) will create a sequence of numbers from 0 to 4, for a total of 5 numbers.
- When we bring all together, the range(5) function will create a sequence of numbers from 1 to 4. Our for loop will iterate over this sequence of numbers, one at a time, making the numbers accessible through the variable x and therefore the code within our loop body will execute for every iteration through the sequence.
- So for the initial loop, x shall contain 0. the next loop,1, and so on until it reaches 4. Once the top of the sequence comes up, the loop will exit, and therefore the code will continue.
- The facility of loops comes from the very fact that it can iterate over a sequence of any quiet data, not just a variety of numbers. We may describe for loops to iterate over an inventory repeatedly for strings, such as usernames or lines during a file.
- Is not sure whether to use a for loop or a short time loop? Always keep in mind that a short time loop is great for performing an action over and over until a condition has changed. A for loop works well once you want to iterate over a sequence of elements.
Infinite loops and Code Blocks
- Another easy mistake that can happen when using loops is introducing an infinite loop.
- An infinite loop is that in which the code block in the loop will continue to execute and never stop.
- This may happen when the condition being evaluated in a while loop doesn’t change.
- Pay close attention to your variables and what possible values they can take. Think about unexpected values, like zero.