Python for loop
In programming, ‘for’ loop is used to repeatedly execute a block of code for certain conditions.
Similarly, in Python ‘for’ loop, we iterate over Python sequences such as list, tuple, set, string, etc. This iteration helps us to execute the statements one by one for Python Sequences.
Example of for Loop
With the help of for loop, we are going to print the list items.
char = ["a", "b", "c", "d"]
for t in char:
print(t)
a
b
c
d
This process is also called iteration.
Example of for Loop
Let’s see a simple Example to loop through the Python Tuple.
char = {"a", "b", "c", "d"}
for t in char:
print(t)
a
b
c
d
Example of for Loop
We can also loop through the set values by the help of the for a loop.
char = {"a", "b", "c", "d"}
for t in char:
print(t)
a
b
c
d
Example of for Loop
We can simply iterate a string as well by the help of the for loop.
char = "TutorialsClass"
for t in char:
print(t)
T
u
t
o
r
i
a
l
s
C
l
a
s
s
Python For Loop – with else statement
Syntax
Like the if statement, we can also use else statement with the for loop.
for x in y:
statement of loop
else:
statement of else
Example of for Loop with else statement
If the condition of a for loop is satisfied then the loop statement will execute. Otherwise, the else statement will execute.
char = ("a", "b", "c", "d")
for t in char:
if t == "b":
continue
print(t)
else:
print("finished")
a
b
c
finished
Python For Loop – Range Function
When we want to repeat a block of code number of times, then we use range()
function.
Example of range() function with for loop
Let’s see a simple example of range()
function with the ‘for’ loop. Here, the default starting value of range is 0 if we pass only one value because the single argument will be treated as stop value.
char = ("a", "b", "c", "d")
for t in range(3):
print(char[t])
a
b
c
Here it starts at 0 and returned till the 3rd element.
Some key points about range() function
- We can also specify the starting of range function such as range(2,6).
- By default, the increment in range function’s range is 1, we can modify it as well passing 3rd argument to the function such as range(30,65,3)
Example of range() function
char = ("a", "b", "c", "d", "e", "f", "g", "h", "j", "k")
for t in range(1, 3):
print(char[t])
print()
for s in range(4, 10, 2):
print(char[s])
b
c
e
g
j
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |