The for
loop in Python is used to iterate over a sequence (like a list, tuple, string, or range). It allows you to execute a block of code repeatedly for each item in the sequence.
Syntax:
for item in sequence:
# code block to be executed for each item
# Python program to print numbers from 0 to 4 using a for loop
# Use a for loop with range()
for i in range(5):
print(f"Number: {i}")
OUTPUT:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Example 2:
# Python program to iterate over a list using a for loop
# Define a list of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Use a for loop to iterate over the list
for fruit in fruits:
print(f"I like {fruit}")
OUTPUT:
I like apple
I like banana
I like cherry
I like date
Example 3:
# Python program to print the multiplication table of a given number
# Input: Get the number from the user
number = int(input("Enter a number to print its multiplication table: "))
# Use a for loop to generate the multiplication table
print(f"Multiplication table for {number}:")
for i in range(1, 11): # Loop through numbers 1 to 10
result = number * i
print(f"{number} x {i} = {result}")
OUTPUT:
Enter a number to print its multiplication table: 5
Multiplication table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Example 4:
# Python program to check if a number is a palindrome using a for loop
# Input: Get the number from the user
number = int(input("Enter a number to check if it's a palindrome: "))
# Convert the number to a string to easily access individual digits
num_str = str(number)
# Initialize a flag variable to True
is_palindrome = True
# Use a for loop to compare digits from the start and end
for i in range(len(num_str) // 2):
if num_str[i] != num_str[-(i + 1)]:
is_palindrome = False
break
# Output the result based on the flag variable
if is_palindrome:
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")
OUTPUT:
Enter a number to check if it's a palindrome: 121
121 is a palindrome.
Enter a number to check if it's a palindrome: 123
123 is not a palindrome.
How it works:
- Input: The program first asks the user to input a number.
- String Conversion: The number is converted to a string to easily access its digits.
- Palindrome Check:
- The
for
loop iterates over the first half of the string. - It compares the digit at position
i
with the digit at position-(i + 1)
(from the end). - If any pair of digits don’t match, it sets
is_palindrome
toFalse
and breaks the loop.
- The
- Output: After the loop, the program checks the
is_palindrome
flag and prints whether the number is a palindrome.