Python for loop

Python for loop is used to iterate over the items of any sequence including python list, string, tuple, etc,…

Python for loop Syntax:

for var_name in sequence: for loop body

Python for loop flow diagram:

Python for loop examples:

1. calculate total value of list values(numeric list)

l=[1,4,3,8,23.0,12.4] total=0 for num in l: total=total+num print("Total value of list is: ", total)

2. Convert strings of list to Upper case using Python for loop:

data={“big”,”data”,”python”,”data science”,”deep learning”]
print(data)

for item in data: print(item.upper()) print(item)

The range() function:

We can generate a sequence of numbers using range() function. It generates consecutive integers based supplied parameters.

range(n): generates a set of whole numbers starting from 0 to (n-1).

Range function Examples:

>>> range(9) [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> range(0,9,2) [0, 2, 4, 6, 8] >>> range(9,0,-2) [9, 7, 5, 3, 1]

3. Python for loop with range function:

for x in range(1,9,2): print(x)

output:
1
3
5
7

Python for loop with else clause:

Python for loop can have am optional else block as well. he else part is executed if the items in the sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Syntax:

for variable in sequence: statements else: statements

Example 4:
items=[1,2,3,4]

for i in items: print(i) else: print("No items left")

Output: