For Loops in Python

In Python, for loops are a fundamental control flow structure used to iterate over sequences like lists, tuples, strings, dictionaries, and even sets.

Purpose

for loops automate the process of going through each element in a sequence, one by one.

They enable you to perform operations, calculations, or modifications on each element within the loop.

Syntax


for item in sequence:
    # Code to be executed for each item

item is a placeholder variable that takes on the value of each element in the sequence during each iteration.

The sequence can be a list, tuple, string, dictionary, or set.

The indented block of code following the : is executed for each item in the sequence.

Examples

1. Printing each element in a list:


fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

2. Iterating over characters in a string:


name = "Sunil"
for char in name:
    print(char)

3. Looping a specific number of times using range():


for i in range(5):  # Range function generates numbers from 0 to 4 (excluding 5)
    print(i)

break and continue Statements:

These statements allow you to control the flow within the loop:

break

Exits the loop prematurely.


numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
    if number == 4:
        break  # Exit the loop when number reaches 4
    print(number)

continue

Skips the remaining statements in the current iteration and moves to the next.


fruits = ["apple", "banana", "orange", "cherry"]
for fruit in fruits:
    if fruit == "banana":
        continue  # Skip banana
    print(fruit)

else Clause

you can add an else clause after the loop to execute code once the entire sequence is iterated through.


for x in range(6):
  print(x)
else:
  print("Finally finished!")

pass Statement

If for loop with no content, put in the pass statement to avoid getting an error.


for x in [0, 1, 2]:
  pass

For Loops Practice and Applications

1. Printing numbers from 1 to 10


for i in range(1, 11):
    print(i)

2. Printing even numbers from 1 to 20


for i in range(2, 21, 2): 
    print(i)

3. Sum of numbers from 1 to 100


total = 0
for i in range(1, 101):
    total += i
print("Sum of numbers from 1 to 100:", total)

4. Calculating the factorial of a number


num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
    factorial *= i
print("Factorial of", num, "is", factorial)

5. Printing a pattern (reverse right triangle)


rows = 5
for i in range(rows, 0, -1):
    print("*" * i)

6. Printing a pattern (diamond shape)


rows = 5
for i in range(1, rows + 1):
    print(" " * (rows - i) + "*" * (2 * i - 1))
for i in range(rows - 1, 0, -1):
    print(" " * (rows - i) + "*" * (2 * i - 1))

7. Counting vowels in a string


string = "Python Programming"
vowels = "aeiouAEIOU"
count = 0
for char in string:
    if char in vowels:
        count += 1
print("Number of vowels:", count)

8. Finding the largest number in a list


numbers = [7, 2, 9, 4, 1, 5]
largest = numbers[0]
for num in numbers:
    if num > largest:
        largest = num
print("The largest number is:", largest)

9. Reversing a String


original_string = "Python"
reversed_string = ""

for char in original_string:
  reversed_string = char + reversed_string  

print("The reversed string is:", reversed_string)

Unsolved Practice Problems with Python For Loops

1. Write a Python program to find the sum of all even numbers from 1 to 100.

2. Write a Python program to count the number of digits in a given integer.

3. Write a Python program to print the multiplication table of a given number.

4. Write a Python program to reverse a given string.

5. Write a Python program to check whether a given number is prime or not.

6. Write a Python program to count the occurrences of a specific character in a given string.

7. Write a Python program to find the factorial of a given number.

8. Write a Python program to check whether a given string is a palindrome or not.

9. Write a Python program to print various patterns (e.g., square, triangle, diamond).

10. Write a program that prompts the user to enter a password. The password must meet the following criteria:

Use a for loop to iterate through the password characters and check if they meet the conditions. Print a message indicating whether the password is valid or not.

11. Given a list of numbers, write a program that calculates the following statistics using for loops:

12. Write a program that analyzes a given text string (you can prompt the user for input) and counts the occurrences of each letter using for loops. Print a dictionary or a table showing the letter and its frequency.

13. Create a guessing game where the user has to guess a randomly generated number between 1 and 10 (or a customizable range). Use a for loop to limit the number of guesses (e.g., 5 guesses). Provide feedback to the user after each guess, indicating if the guess is higher, lower, or correct.

Intermediate Level

14. Write a Python program to find all prime numbers within a given range.

15. Write a Python program to print Pascal's triangle up to a specified number of rows.

16. Write a Python program to find all Armstrong numbers within a given range.

17. Write a Python program to sort a list of integers in ascending order.

18. Write a Python program to find all perfect numbers within a given range.

19. Write a Python program to print advanced patterns (e.g., pyramid, hollow diamond).