Javatpoint Logo
Javatpoint Logo

How to use for loop in Python

Python for loop iterate over the sequences. It repeats the piece of code n number of times. Consider the following flowchart of for loop.

Flowchart

How to install OpenCV in Python

Python for loop can be used in two ways.

  • Using Sequence
  • Using range() function

Using Sequence

The sequence is referred to as list, set, string, tuple, and dictionary in Python. We can extract the elements of the sequence using for loop. Below is the syntax for loop.

Syntax:

Let's understand the following example.

Example - 1

Output:

10
20
30
40
50
60

Example - 2

Output:

J
a
v
a
T
p
o
i
n
t

Using the range() function

The range function() generates the sequence of the numbers. For example, if we execute the range(5) and it will generate the 0 to 4. The syntax of the range() function is given below.

Syntax:

It accepts the three arguments.

  • The start represents the beginning of the iteration.
  • The stop indicates the end of for loop. It will iterate till stop-1.
  • The step size skips the specific number of iteration. By default, the step size is 1.

Let's understand the following example.

Example - 1

Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Example - 2 Traverse the List element using range() function

Output:

Hii Peter
Hii Joseph
Hii Ricky
Hii Devansh
Hii Kevin

Explanation:

The len() function returns the length of the list. The range() got the number of elements in the list and printed its elements.






Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA