Python Tutorials

Python Programs

Python For Loop


Python For Loop

In this tutorial, we will learn about for loops in Python. We will cover the basics of iterative execution using for loops.


What is a For Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.


Syntax

The syntax for the for loop in Python is:

for item in iterable:
    # Code block to be executed

The for loop iterates over each item in the iterable object (such as a list, tuple, or string) and executes the code block for each item.



Printing Numbers from 1 to 10

  1. Use a for loop to print numbers from 1 to 10.

Python Program

for i in range(1, 11):
    print(i, end=' ')

Output

1 2 3 4 5 6 7 8 9 10 


Calculating the Factorial of a Number

  1. Use a for loop to calculate the factorial of a number.

Python Program

n = 5
factorial = 1
for i in range(1, n + 1):
    factorial *= i
print(f"Factorial of {n} is {factorial}")

Output

Factorial of 5 is 120


Summing the Elements of a List

  1. Use a for loop to calculate the sum of the elements in a list.

Python Program

arr = [1, 2, 3, 4, 5]
sum = 0
for num in arr:
    sum += num
print(f"Sum of the elements in the list is {sum}")

Output

Sum of the elements in the list is 15