Loops In Python
For Loops
The
forloop is used to iterate over items and execute code on each item.It has two keywords,
forandin, which are used to describe the element and the object that is being iterated over, respectively.The indentation after
:starts the body of the loop.
In the example below, the
forloop is iterating over the listnums. For each item innum, it is printing the output ofnum + 1.
numbers = [2, 4, 6, 8, 10, 12, 14]
for number in numbers:
print (num**2)nums = [1, 2, 3, 4, 5]
for num in nums:
print(num + 1)
This will output:
2
3
4
5
6
For loops with Range()
The
range()function can be used with theforloop to execute a block of code multiple times. The code below iterates between numbers0to2and prints each number.
for i in range (4)
print (i)for i in range(3):
print(i)
Nested for Loops
A for loop can have nested for loops. This is particularly useful if the items you are iterating over contain subitems. In the example below, we have a list of lists called teams and we can use a nested for loop to print each name in the lists.
fruits = [['Watermelon', 'Cherry'],['Strwaberry', 'Raspberry']]
for fruit in fruits:
for name in fruit :
print (name)
#identation is important teams = [['Jody', 'Abe'], ['Abhishek', 'Kim'], ['Taylor', 'Jen']]
for team in teams:
for name in team:
print(name)
While Loops
The while loop is used to execute code while its condition evaluates to be True. In the example below, the while loop will run and print i as long as the value of iis less than 6.
i=20
while i<100 :
print (i)
i+=20i = 1
while i < 6:
print(i)
i += 1
Infinite Loops
An infinite loop is a
whileloop that never terminates because the condition is always evaluated to beTrue.This could be due to a typo or an incorrect logic in the loop. You can terminate the loop by pressing the
Ctrlandctogether on your keyboard.