In this tutorial, we are going to discuss how to print all square numbers up to a given number in Python by using a while loop.
As we know in mathematics square numbers have a great concept.
In mathematics, square numbers are numbers that can be represented in the form of the product of an integer by itself.
Simple Code:
n = int(input("Enter the value of n: "))
i = 1
while i*i <= n:
print(i*i, end=" ")
i += 1
Output:
Enter the value of n: 20
1 4 9 16
Code with comments:
# take input from user for the value of n
n = int(input("Enter the value of n: "))
# initialize i to 1
i = 1
# use a while loop to generate square numbers up to n
while i*i <= n:
# print the current square number
print(i*i, end=" ")
# increment i by 1
i += 1
Explanation:
We first take input from the user for the value of n, up to which we want to generate square numbers.
We initialize i to 1.
Then, we use a while loop to generate square numbers up to n.
In each iteration of the loop, we check if i*i is less than or equal to n.
If it is, we print i*i, which is the current square number.
We also increment i by 1 in each iteration of the loop.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.