Mark As Completed Discussion

For Loops

For loops are used to iterate over a sequence of elements. They are used when a code block needs to be repeatedly executed a known number of times.

In Python, for loops can be used in two ways; using the range keyword and without using the range keyword. range keyword is used to specify how many times the code block of the loop needs to be repeated. It always takes an integer (a variable of type int or a value of type int) as a parameter.

For example, suppose you want to print a list of numbers from 0 to 9. This is an integer sequence, and hence the range keyword is used.

PYTHON
1#prints a sequence of numbers from 0 to 9
2for i in range(10):
3    print(i)

The range keyword can also be used to access sequences using len() method and indexing property. In the below example, len() gives the length of the list (which is 5 here). The loop is thus repeated 5 times, and each time an element from the list is accessed using indexing to print all elements in the list.

PYTHON
1#prints all values in the vegetables list using indices
2vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for i in range(len(vegetables)):
4    print(vegetables[i])

For loops can be used without the range keyword as well. In that case, elements in the sequence are directly accessed by specifying the variable name of the iterable.

PYTHON
1#prints all values in the vegetables list one by one
2vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for i in vegetables:
4    print(i)