Python For Loop
What is For Loop in Python?
Iterating through a sequence is done with a For loop. This is more like an iterator method seen in other object-oriented programming languages than the For keyword in other programming languages.
The For loop allows us to run a sequence of statements once for each item in a list, tuple, set, or other data structure.
Python for loop Syntax
for ( init; condition; increment ) :
# Print each fruit in a fruit list: fruits = ["pear", "melon", "orange"] for x in fruits: print(x)
In Python, the
range() function returns the sequence of numbers inside a given range.
range() method returns a number series that starts at 0 and advances by 1 (by default) until it reaches a given value.
Make a sequence of numbers from 0 to 6, and print each item in the sequence:
for n in range(7): print(n)
range() method has a default beginning value of 0. But you may change it by passing it a parameter: range(1, 5), which indicates numbers from 1 to 5 (but not including 5).
for n in range(1,5): print(n)
range() method increases the sequence by one, by default. However a third parameter can be used to set the increment value: range(1, 10,2) is a function that takes numbers from 1 to 10 (but not including 10) and adds 2 to the sequence.
for n in range(1,10,2) : print(n)
range() method increments the sequence by 1, by default. However, a third parameter can be used to set the increment value: range(10,5,-1): range(10,5,-1), which means values from 10 to 5 (but not including 5) and decrement the sequence by -1.
for n in range(10,5,-1) : print(n)
For loop with else
In a For loop, the else keyword indicates a block of code that will be performed after the loop is finished:
Print all numbers from 0 to 6, and print a message when the loop has ended:
for y in range(7): print(y) else: print("finished! ")
The For loop is used in Python to iterate over a series of objects such as a list, string, tuple, and other iterable objects like range.
# outer loop for x in range(1, 10): # nested loop # to iterate from 1 to 9 for y in range(1, 10): # print multiplication print(x * y, end=' ') print()
What will be the outcome of the Python code below?
x = ['a', 'c']
for i in x:
Select the correct answer