Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
Reading time: 20 minutes | Coding time: 2 minutes
Sometimes, we might want to perform the same thing multiple times. In these situations we use loops. Loops are used for iterating over a sequence. There are two types of loops in python. They are
- For Loop
- While Loop
In this article we are going to discuss about the for loop in Python and answer the following questions:
- Can a For loop print the elements of a List and Tuple?
- Can a For Loop be used for a String?
- Can for loops be nested?
- How to use Range function in For loop?
- How are Continue and Break Statements used in For Loop?
Syntax
Unlike in C and C++ for loop has a different syntax in python.
for iterator in sequence:
execute this statement
Can a For loop print the elements of a List and Tuple?
Yes, a for loop can be used to traverse both list and tuple.
For a List
>>> List = ["Yellow",12.34,100]
>>> for i in List:
print(i)
Yellow
12.34
100
For a Tuple
>>> tuple = ("Java", 10)
>>> for i in tuple:
print(i)
Java
10
Can a For Loop be used for a String?
Yes, we can use a for loop to traverse the characters in a string.
>>> for i in "Python":
print(i)
P
y
t
h
o
n
Can for loops be nested?
Nested for loops are supported by Python and are commonly used. In Nested For loops we use a for loop inside a for loop
>>> animals = ["Cat","Dog","Rat"]
>>> colors = ["Yellow","Red","Orange"]
>>> for m in animals:
for n in colors:
print(m,n)
Cat Yellow
Cat Red
Cat Orange
Dog Yellow
Dog Red
Dog Orange
Rat Yellow
Rat Red
Rat Orange
How to use Range function in For loop?
We can also use range function in a for loop to declare the range for the iterating variable.
>>> for i in range(0,5):
print(i+1)
1
2
3
4
5
How are Continue and Break Statements used in For Loop?
We can also use continue and break statements in a for loop
Break Statement
The break statement is used when we want to stop the iteration and break(exit) the loop.
>>> for i in tuple:
if i == 10:
break
print(i)
Hi
12
Here when i=10 the loop is broken. Hence the print statement is not executed for i=10 and for i="Hello".
Continue Statement
The continue statement is used when we want to stop the iteration and continue with the next statement.
>>> for i in range(0,6):
if i == 3:
continue
print(i+1)
1
2
3
5
6
In the above example for i=3 the loop is broken and print statement is not executed. Again from i=4 the iteration is continued.