Loop based Examples
Example 1: Print Numbers from 1 to 10
This simple example uses a for loop to print numbers from 1 to 10.
for i in range(1, 11):    print(i)Output:
12345678910
Explanation:
range(1, 11)generates numbers from 1 to 10 (the upper limit 11 is exclusive).- The loop iterates through these numbers, printing each one.
 
Example 2: Calculate the Sum of a List of Numbers
This example demonstrates how to use a for loop to calculate the sum of numbers in a list.
numbers = [2, 4, 6, 8, 10]total = 0for num in numbers:    total += numprint("The total sum is:", total)Output:
The total sum is: 30
Explanation:
- The loop iterates through each number in the 
numberslist, adding it to thetotalvariable. - After the loop finishes, the total sum is printed.
 
Example 3: Print Each Character of a String
This example uses a for loop to iterate through each character in a string and print it.
word = "Python"for letter in word:    print(letter)Output:
Python
Explanation:
- The loop iterates through each character in the string 
"Python", printing each character on a new line. 
Example 4: Find the Factorial of a Number
This example shows how to use a for loop to calculate the factorial of a given number.
number = 5factorial = 1for i in range(1, number + 1):    factorial *= iprint("The factorial of", number, "is:", factorial)Output:
The factorial of 5 is: 120
Explanation:
- The loop multiplies each number from 1 to 5 together, storing the result in 
factorial. - The factorial of 5 (which is 
5 * 4 * 3 * 2 * 1) is calculated as 120. 
Example 5: Nested for Loop to Print a Pattern
This example demonstrates a nested for loop to print a simple pattern.
for i in range(1, 6):    for j in range(i):        print("*", end="")    print()Output:
***************Explanation:
- The outer loop runs 5 times, each time increasing the value of 
i. - The inner loop prints 
*as many times as the current value ofi. end=""is used to print stars on the same line, andprint()without arguments moves to the next line after each row.
Example 6: Find the Largest Number in a List
This example uses a for loop to find the largest number in a list.
numbers = [3, 7, 2, 8, 5, 10, 1]max_num = numbers[0]for num in numbers:    if num > max_num:        max_num = numprint("The largest number is:", max_num)Output:
The largest number is: 10
Explanation:
- The loop iterates through each number in the list.
 - If the current number is larger than 
max_num, it updatesmax_numto the current number. - At the end of the loop, 
max_numcontains the largest number in the list. 



0 Comments
Please do note create link post in comment section