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 ) :
# statement(s)
Code:
# Print each fruit in a fruit list:
fruits = ["pear", "melon", "orange"]
for x in fruits:
print(x)
Output:
range() functions
In Python, the range()
function returns the sequence of numbers inside a given range.
The range()
method returns a number series that starts at 0 and advances by 1 (by default) until it reaches a given value.
Example:
Make a sequence of numbers from 0 to 6, and print each item in the sequence:
for n in range(7):
print(n)
Output:
The 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).
Example 1:
for n in range(1,5):
print(n)
Output:
The 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.
Example 2:
for n in range(1,10,2) :
print(n)
Output:
The 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.
Example:
for n in range(10,5,-1) :
print(n)
Output:
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:
Example:
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! ")
Output:
Nested loop
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.
Example:
# 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()
Result:
QUIZ!
What will be the outcome of the Python code below?
x = ['a', 'c']
for i in x:
i.upper()
print(x)
Select the correct answer