Python for loops

Python For Loop

TaskIn Python, a for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. It’s a common way to perform repeated actions on elements of a sequence.

Syntax:
for variable in sequence:

In above syntax, variable is the value accessed by the loop.
Sequence can be a list, tuple, dictionary, set, or string

There are various ways of using for loop in python as follows:

1. Standard for loop over a list or sequence
The most common use of the for loop is iterating over a sequence such as a list, tuple, or string.
Example: loop over a list

number_list = [1, 2, 3, 4] #creating a list called number_list
for number in number_list: #initializing for loop that will iterate # on each element one by one till the end of list
print(number, end=’ ’) #printing number (element) one by one
#Output: 1 2 3 4

Explanation:

number_list = [1, 2, 3, 4]

creating a list called number_list

for number in number_list:

initializing for loop that will iterate on each element one by one till the end of list

print(number)

printing number (element) one by one

range() function:
The range() function in Python is used to generate a sequence of numbers, which is useful when iterating over a set of values. It’s commonly used in loops, particularly in for loops, to repeat a block of code a specific number of times.

Syntax:
range(start, stop, step)

Parameters:
    ● start: (Optional) The starting point of the sequence. Default value is 0 if not provided.
    ● stop: (Compulsory) The endpoint of the sequence. The loop will stop before reaching this value.
    ● step: (Optional) The difference between each number in the sequence. Defaults to 1 if not provided.

2. For loop with range():
This is used to loop over a sequence of numbers, which can be helpful if you know how many times you want to iterate.
 
Syntax:
for i in range(start,stop,step):
# your block of code
 
Example:
Write a program to print Sum of all number from 1 to 5 i.e. 1 + 2 + 3 + 4 + 5 = 15 using for Loop i.e define the loop from 1 to 5

sum = 0 #creating a variable sum with value 0
for i in range(1,6): #for loop that will run five times 1-5
sum += i #sum = sum + i
print(f”Sum of 1 to 5 is {sum}”) #Output: Sum of 1 to 5 is 15

Explanation:

sum = 0

creating a variable sum with value 0

for i in range(1,6):

For loop with iterative variable i that will run five times (1 to 5). 6th Iteration will not run as it will not include 6.
Here, step is not mentioned so it will take 1 as default.

    sum += i

Assigning sum = sum + i. For first iteration value of sum will be 0 and value of i will be
one so sum = 0 + 1 = 1

For second iteration the value of sum = 1 and value of i will be equal to 2 so
sum = 1 + 2 = 3
For third iteration, now the value of sum is 3 and value of i is 3 so sum = 3 + 3 = 6
For fourth iteration, now the value of sum is 6 and value of i is 4 so sum = 6 + 4 = 10
For fifth iteration, now the value of sum is 10 and value of i is 5 so sum = 10 + 5 = 15
Now, as 5 iterations are completed from i = 1 to i = 5, loop will stop executing as it was
instructed to stop on 6.

3.Nested For Loop
A for loop inside another for loop, often used for iterating over multidimensional data.

Syntax:
for iterable_variable1 in range(start,stop,step):
for iterable_variable2 in range(start,stop,step):
# do something with iterable_variable1 and iterable_variable2
Example:

matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
for row in range(3):
for col in range(3):
print(matrix[row][col], end=’ ‘)
print()
”’
Output:
0 1 2
3 4 5
6 7 8
”’

Explanation:

matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]

Declaring 3*3 multidimensional list (matrix)

for row in range(3):        #OUTER LOOP

First for loop(Outer loop), this loop will run 3 times (As it is a 3*3 matrix)

for col in range(3):   #INNER LOOP

Second loop (Inner Loop), this loop will run 3 times

 print(matrix[row][col], end=’   ‘)

This will print the value of matrix element at current index of row and col
Following table represents matrix the value are in black and index of value (row,col) are
in red respectively.

First Iteration of Outer Loop (row = 0):
So, for first iteration of inner loop where row = 0 and col = 0, it will print 0 which is at (0,0),
In second iteration of inner loop, now row = 0 and col = 1, it will print 1 which is at (0,1),
In third iteration of inner loop, now row = 0 and col = 2, it will print 2 which is at (0,2),

All 3 iterations of inner loop are completed so it will go on next line of code i.e.

    print()

This will take the new line

Output till now:

0   1   2  

Second Iteration of Outer Loop (row = 1):
Now, Outer loop is incremented i.e. row = 1, and again inner loop will start from 0 i.e. 
col=0
    ○ So, for the first iteration of inner loop where row = 1 and col = 0, it will print 3 which is at (1,0),
    ○ In second iteration of inner loop, now row = 1 and col = 1, it will print 4 which is at (1,1),
    ○ In third iteration of inner loop, now row = 1 and col = 2, it will print 5 which is at (1,2),             

    print()

This will take the new line

Output till now:

0 1 2
3 4 5

Third Iteration of Outer Loop (row = 2):
Now, Outer loop is incremented i.e. row = 2, and again inner loop will start from 0 i.e. 
col=0
    ○ So, for the first iteration of inner loop where row = 2 and col = 0, it will print 6 which is at (2,0),
    ○ In second iteration of inner loop, now row = 2 and col = 1, it will print 7 which is at (2,1),
    ○ In third iteration of inner loop, now row = 2 and col = 2, it will print 8 which is at (2,2),
 
All 3 iterations of inner loop are completed so it will go on next line of code i.e.

    print()

This will take the new line

Now, all three iterations of the outer loop are completed so the loop will end.

Final Output:

0 1 2
3 4 5
6 7 8

4. For loop with string
In this case, we can use a for loop to access each character of the string one by one.
Syntax:
for char in string:
#do something with char
Example:

my_str = ‘Jannat’
for chr in my_str: #loop will access each char of my_str 1 by 1
print(chr,end=’ ‘) #printing chr 1 by 1

#Output: J a n n a t

5. For loop with else
In this case, after a for loop completes its execution, the else block runs for once.
Syntax: 
for i in range(stop):
#block of code
else:
#block of code
Example:

for i in range(3):
print(i, end=’ ’)
else:
print(“\nLoop finished!”)
#Output:
#0 1 2
#Loop Finished

Examples:
Example 1: Calculating the Sum of a List

numbers = [10, 20, 30, 40, 50]
total = 0
for number in numbers:
total += number
print(f”The total sum is: {total}”)
#Output: The total sum is: 150

Explanation:

numbers = [10, 20, 30, 40, 50]

A list named numbers is created with five elements: 10, 20, 30, 40, and 50. This list represents the numbers you want to sum.

total = 0

A variable total is initialized with the value 0.

for number in numbers:

This is the start of a for loop that will iterate over each element (or “number”) in the numbers list. The variable number takes the value of each item in the list one by one (i.e., 10, then 20, and so on).

    total += number

During each iteration of the loop, the current value of the number is added to the total. The += operator is shorthand for total = total + number.
Here’s how it works during each iteration:
1st iteration: total = 0 + 10 → total = 10
2nd iteration: total = 10 + 20 → total = 30
3rd iteration: total = 30 + 30 → total = 60
4th iteration: total = 60 + 40 → total = 100
5th iteration: total = 100 + 50 → total = 150

print(f”The total sum is: {total}”)

Once the loop finishes iterating over all the numbers, the print() function outputs the final value of total (which is 150).

Example 2: List Comprehension for Squaring Numbers

numbers = [1, 2, 3, 4, 5]
squared_numbers = [number**2 for number in numbers]
print(squared_numbers)
#Output: [1, 4, 9, 16, 25]

Explanation:

numbers = [1, 2, 3, 4, 5]

A list named numbers is created with the elements [1, 2, 3, 4, 5]. This list contains five integers that will be squared in the next step.

squared_numbers = [number**2 for number in numbers]

This is a list comprehension, a concise way to create a new list by applying an expression to each item in an existing list.

Here’s the breakdown:
number**2: This expression takes each number from the numbers list and squares it. In Python, ** is the exponentiation operator, so number**2 means “number raised to the power of 2” (or number * number).
for number in numbers: This part go through each element in the numbers list. For each iteration, the number takes on the value of the current element (e.g., 1, 2, 3, etc.).

Here’s how it works during each iteration:
1st iteration: 1**2 = 1
2nd iteration: 2**2 = 4
3rd iteration: 3**2 = 9
4th iteration: 4**2 = 16
5th iteration: 5**2 = 25
So, the final squared_numbers list will be: [1, 4, 9, 16, 25].

print(squared_numbers)

The print() function outputs the value of the squared_numbers list.

Example 3: Printing reverse of a list

numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=’ ‘)
#Output: 5 4 3 2 1

Explanation:

numbers = [1, 2, 3, 4, 5]

A list named numbers is created with the elements [1, 2, 3, 4, 5]. This list contains five integers.

for number in reversed(numbers):

This is a for loop that iterates over the list numbers in reverse order.
The reversed() function takes the numbers list and returns a list in which the items are in reverse order. So, instead of iterating through [1, 2, 3, 4, 5], it will iterate through [5, 4, 3, 2, 1].

    print(number, end=’ ‘)

The print() function is used to output each number from the reversed list. The end=’ ‘ argument specifies that after printing each number, a space (‘ ‘) will be added instead of the default newline character (‘\n’).As a result, the numbers will be printed on the same line, separated by spaces.
Task:
1. You need to create a program that prints the multiplication table of a given number using a for loop. The program should display the multiplication table from 1 to 10 for the specified number.

First you have to take input from console

Output

After giving input you have to show like this same as below
Output

2. Print Even Numbers:
Use a for loop to iterate from 1 to 20.
Inside the loop, use an if-else statement to print only even numbers.

3. Sum of Multiples of 3:
Use a for loop to iterate from 1 to 30.
Inside the loop, use an if-else statement to check if the number is a multiple of 3.
Sum the multiples of 3 and print the result at the end.

4. Weekday/Weekend Checker:
Use a for loop to iterate through an array of days of the week (“Monday”, “Tuesday”, etc.).
Inside the loop, use if-else statement to print “Weekday” for Monday to Friday and “Weekend” for Saturday and Sunday.

5. Grade Classifier:
Use a for loop to iterate through an array of grades (‘A’, ‘B’, ‘C’, ‘D’, ‘F’).
Inside the loop, use a if-elif-else statement to print the description of each grade.
use an if-else statement to print a motivational message for grades A and B.

6. Month Days Printer:
Use a for loop to iterate through an array of month numbers (1 to 12).
Inside the loop, use a if-elif-else statement to print the number of days in each month.

7. Identify Prime Numbers:
Use a for loop to iterate from 1 to 50.
Inside the loop, use an if-else statement to check if the number is prime.
Print the prime numbers.
8. Basic Iteration:
Write a program that uses a for loop to iterate over a list of integers and print each value

9. Summing Elements:
Given a list of integers, use a for loop to calculate and print the sum of all the elements.

10. Finding Maximum Value:
Write a program that uses a for loop to find and print the maximum value in a list of integers.

11. Counting Elements:
Use a for loop to count how many elements in a list of integers are greater than a specified value.

12. String Lengths:
Given a list of strings, use a for loop to print each string and its length.
list_of_string = [‘Hello’, ‘Hi’, ‘Wassup’, ‘Hola’]

Course Video

YouTube Reference :