For loop in Python is the most widely used looping construct and in this post, you will learn how to use the for loop in solving real-life problems.
The syntax for creating a for loop is:
for num in numbers: #perform action
The above statement tells the interpreter to retrieve the first value in the numbers and store it in a variable num, and the process repeats until it gets to the last item in the list – numbers.
Using the for loop to iterate on a list
The number of repetitions obtainable in a for loop is the same as the number of items in the sequence that it is iterating.
Consider the example below where the for loop is used to loop over a list with 5 items.
fruits = ['apple', 'orange', 'mango', 'guava', 'pineapple'] for fruit in fruits: print('looping') #outcome #looping #looping #looping #looping #looping
From the outcome of the example above, you can see that looping is printed 5 times, which is the number of items in the list – fruits.
However, a lot of times, you would want to use the value of the iterable during each stage of the looping to perform an action. Instead of just printing looping, you may wish to print the values in the iterable.
fruits = ['apple', 'orange', 'mango', 'guava', 'pineapple'] for fruit in fruits: print(fruit) #outputs #apple #orange #mango #guava #pineapple
For loop Examples
In order to understand how the for loop works better, the following examples will be of immense help.
For loop with Strings
A string in Python is a sequence of characters. The example below uses the for loop to iterate on the characters making up a string.
for char in 'hello': print(char) #output # h # e # l # l # o
Printing Natural numbers using the range() function
The example below makes use of the for loop and the range() function to print natural numbers from 1 to 10.
for num in range(1,11): print(num) #output # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10
Let’s say that you don’t want to print out the numbers, you may decide to append the numbers to an empty list as shown below:
numbers = [] for num in range(1,11): numbers.append(num) print(numbers) #output # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Calculating sum and average with for loop
The example below uses the for loop to calculate the sum and average of the numbers in a list.
numbers = [10, 20, 30, 40, 50] sum = 0 for num in numbers: sum +=num avg = sum/len(numbers) print(f'Sum: {sum}') print(f'Average: {avg}') #output # Sum: 150 # Average: 30.0
Counting digits in a number
Consider that you want to count the number of digits in a number.
Naturally, you can easily convert the number to a string, using the str() function and determine the number of digits using the len() function.
Yet, you can also use the for loop to achieve the same thing as shown below:
num = 112 print(len(str(num))) #output - 3 #using the for loop count = 0 for digit in str(num): count+=1 print(count) #output - 3
Printing prime numbers
Prime numbers are numbers that are not divisible by any number apart from 1 and itself. Using the for loop, this is a list of all the prime numbers from 1 to 100.
In this case, we used for else statement.
prime = [] for num in range(2, 101): for i in range(2, num): if (num % i) == 0: break else: prime.append(num) print(prime) #output #[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, #43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Calculating factorial
Factorial is an important function in mathematics used mainly for permutations and combinations.
Factorial is a multiplication operation of natural numbers with all the natural numbers that are less than it. In order words, the factorial of 5 is the same as 5x4x3x2x1 = 120.
Using the for loop, the following program can compute the factorial of any number.
num = 5 factorial = 1 for num in range(1, num+1): factorial *= num print(f'The factorial of {num} is {factorial}') #output # The factorial of 5 is 120
Nested for loop
You can combine more than one for loop to achieve complicated results. A for loop inside another for loop is considered a nested for loop.
Let’s say you want to print out a multiplication table from 1 to 10. Here is how you can do so by nesting a for loop inside another for loop.
for i in range(1,11): for j in range(1,11): print(f'{i} x {j} = {i * j}')