Class 11 Some example based on for loop

 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:

1
2
3
4
5
6
7
8
9
10

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 = 0
for num in numbers:
total += num
print("The total sum is:", total)

Output:

The total sum is: 30

Explanation:

  • The loop iterates through each number in the numbers list, adding it to the total variable.
  • 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:

P
y
t
h
o
n

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 = 5
factorial = 1
for i in range(1, number + 1):
factorial *= i
print("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 of i.
  • end="" is used to print stars on the same line, and print() 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 = num
print("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 updates max_num to the current number.
  • At the end of the loop, max_num contains the largest number in the list.

Post a Comment

0 Comments