Write a python program to print the square of all numbers from 1 to 10

1. Introduction

In this blog post, we'll develop a Python program to print the square of all numbers from 1 to 10. This task will illustrate the use of loops in Python, specifically the for loop, which is a fundamental concept in Python for iterating over a sequence of numbers.

2. Program Steps

1. Use a for loop to iterate over a range of numbers from 1 to 10.

2. Calculate the square of each number.

3. Print the square of each number.

3. Code Program

def print_squares_1_to_10():
    # Step 1: Iterate over numbers from 1 to 10
    for number in range(1, 11):
        # Step 2: Calculate the square of the number
        square = number ** 2

        # Step 3: Print the square
        print(f"Square of {number} is {square}")

# Call the function
print_squares_1_to_10()

Output:

The output will display the squares of numbers from 1 to 10:
Square of 1 is 1
Square of 2 is 4
...
Square of 10 is 100

Explanation:

1. The for loop is used with range(1, 11), which generates a sequence of numbers from 1 to 10.

2. Inside the loop, we calculate the square of the current number using the expression number ** 2.

3. Each calculated square is then printed using the print function. The f-string (formatted string literal) is used for including the variables directly in the string, providing a readable and concise way to display the result.

This program effectively demonstrates how to use a for loop in Python to perform and display calculations on a sequence of numbers.


Comments