For Loop
The for loop in Python is utilized to repeat over a succession (list, tuple, string) or other iterable items. Iterating over a arrangement is called traversal.
Syntax of for Loop
for val in sequence:loop body
Here, val is the variable that takes the value of the thing inside the sequence on every iteration.
Loop go on until we reach the last item in the grouping. The body of for loop is isolated from the remainder of the code utilizing indentation.
Example: Python for Loop
"""Program to find the sum of all numbers
stored in a list """
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:-
The sum is 48The range() function
We can produce a sequence of numbers utilizing range() function. range(10) will produce numbers from 0 to 9 (10 numbers).
We can likewise characterize the beginning, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not gave.
The range object is "lazy" in a sense because it doesn't produce each number that it "contains" when we make it. However, it is not an iterator since it upholds in, len and __getitem__ operations.
This function doesn't store all the values in memory; it would be wasteful. So it recalls the beginning, stop, step size and creates the next number on the go.
To drive this function to output all the items, we can utilize the function list().
The following example will explain this.
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Output:-
range(0, 10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
We can utilize the range() function in for loops to repeat through a grouping of numbers. It can be joined with the len() function to repeat through a sequence utilizing indexing. Here is an example.
"""Program to iterate through a list
using indexing """
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
Output:-
I like popI like rock
I like jazz
python for loop with else
A for loop can have an discretionary else block as well. The else part is executed if the items in the things utilized in for loop exhausts.
The break keyword can be utilized to stop a for loop. In such cases, the else part is disregarded.
Hence, a for loop's else part runs if no break happens.
Here is an example to outline this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:-
0 1 5No items left.
0 Comments
🙏🙏please don't enter any spam links on the comment box.....