/    /  Python – For Loop

Python – For Loop:

In this tutorial, we will learn about for loop. In Python, for loop is used to iterate over the sequence of elements (the sequence may be list, tuple or strings.. etc). Below is the syntax.

Syntax:

for_stmt ::=  "for" target_list "in" expression_list ":" suite

              ["else" ":" suite]

In the below example, we have given the list of strings as courses and the for loop created to iterate through all the strings to print the course and the length of the course name.

Example:

>>> courses=['html','c','java','css']

>>> for i in courses:

...     print(i, len(i))

...

html 4

c 1

java 4

css 3

>>> 

In the below example, for loop iterates through the list of numbers. In the immediate step, if statement filters only the numbers less than 50, else it will display “no values” for rest of the iterations.

Example:

>>> x=[10,20,30,40,50,60]

>>> x

[10, 20, 30, 40, 50, 60]
>>> for i in x:

...     if i<50:

...             print(i)

...     else:

...             print("no values")

...

Below is the output:

10

20

30

40

no values

no values