For loop practice questions

Below are 10 Python for loop questions, ranging from beginner to intermediate levels, complete with code solutions. These questions are designed to help beginners get comfortable with the concept of loops in Python, as well as challenge them a bit as they progress.

1. Sum of First N Natural Numbers

Question: Write a Python program that uses a for loop to calculate the sum of the first N natural numbers.

N = 10  # Example, can be any positive integer
sum = 0
for i in range(1, N+1):
    sum += i
print("Sum of the first", N, "natural numbers is:", sum)

2. List of Squares

Question: Generate a list of the squares of the first 10 positive integers.

squares = []
for i in range(1, 11):
    squares.append(i**2)
print(squares)

3. Character Count

Question: Count the number of vowels in a given string using a for loop.

input_string = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for char in input_string:
    if char in vowels:
        count += 1
print("Number of vowels:", count)

4. Reverse a String

Question: Reverse a given string using a for loop.

input_string = "Hello World"
reversed_string = ""
for char in input_string:
    reversed_string = char + reversed_string
print("Reversed String:", reversed_string)

5. Fibonacci Sequence

Question: Generate the first 10 numbers of the Fibonacci sequence.

a, b = 0, 1
for i in range(10):
    print(a, end=' ')
    a, b = b, a+b

6. Factorial of a Number

Question: Calculate the factorial of a given number N.

N = 5  # Example, can be any non-negative integer
factorial = 1
for i in range(1, N + 1):
    factorial *= i
print("Factorial of", N, "is:", factorial)

7. Multiplication Table

Question: Print the multiplication table of a given number up to 10.

num = 7  # Example, can be any positive integer
for i in range(1, 11):
    print(num, 'x', i, '=', num*i)

8. List Elements Greater than N

Question: Given a list, use a for loop to print all the elements greater than N.

my_list = [1, 4, 12, 7, 8, 9]
N = 5
for item in my_list:
    if item > N:
        print(item)

9. Count Even and Odd Numbers in a List

Question: Count the number of even and odd numbers from a given list.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_count, odd_count = 0, 0
for number in my_list:
    if number % 2 == 0:
        even_count += 1
    else:
        odd_count += 1
print("Even numbers in the list:", even_count)
print("Odd numbers in the list:", odd_count)

10. Prime Numbers Within a Range

Question: Find all prime numbers in a given range from 2 to N.

N = 20  # Example, can be any positive integer
for num in range(2, N + 1):
    for i in range(2, num):
        if (num % i) == 0:
            break
    else:
        print(num, end=' ')

These questions are tailored to gradually increase in difficulty, helping beginners to not only understand the for loop in Python but also to practice some common patterns and algorithms.