Python 'for' Loops Practice with Comments and Outputs
Question 1: Write a `for` loop that prints the numbers from 1 to 5 (inclusive).
for i in range(1, 6):
print(i)
Comments: This loop iterates from 1 to 5 and prints each number in the range.
Output:
Question 2: Write a `for` loop that prints all even numbers from 2 to 10 (inclusive).
for i in range(2, 11, 2):
print(i)
Comments: Using a step of 2 ensures only even numbers are printed.
Output:
10
Question 3: Write a `for` loop that calculates the sum of all numbers from 1 to 100 (inclusive).
total_sum = 0
for i in range(1, 101):
total_sum += i
print(total_sum)
Comments: The loop adds each number in the range to the total_sum variable.
Output:
5050
Question 4: Write a `for` loop that prints the multiplication table for the number 5 (from 1 to
10).
for i in range(1, 11):
print(f"5 x {i} = {5 * i}")
Comments: The loop uses formatted strings to generate the multiplication table.
Output:
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50