def perfect_squares(start, end):
squares = []
for num in range(start, end + 1):
if (num ** 0.5).is_integer():
squares.append(num)
return squares
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
print(perfect_squares(start, end))
Code Explanation:
1. Defining the Function
def perfect_squares(start, end):
def: This keyword is used to define a new function in Python.
perfect_squares: The name of the function, which suggests its purpose (to find perfect squares).
start, end: These are the input arguments (parameters). start is the lower bound of the range, and end is the upper bound.
2. Initializing an Empty List
squares = []
squares: This is an empty list that will store all the perfect squares found within the given range.
3. Iterating Through the Range
for num in range(start, end + 1):
for num in range(start, end + 1):
A for loop that iterates over each number from start to end (inclusive).
range(start, end + 1): Generates a sequence of numbers starting at start and ending at end.
4. Checking for Perfect Squares
if (num ** 0.5).is_integer():
num ** 0.5: Calculates the square root of the current number (num).
.is_integer(): Checks if the square root is an integer.
If the square root is a whole number, it means num is a perfect square.
5. Adding Perfect Squares to the List
squares.append(num)
squares.append(num): Adds the current number (num) to the squares list if it passes the perfect square check.
6. Returning the List
return squares
return squares: After the loop finishes, the function returns the list of all perfect squares found within the range.
7. Taking User Input for the Range
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
input(): Displays a prompt to the user and reads their input as a string.
int(): Converts the user input from a string to an integer.
The user is asked to provide the starting (start) and ending (end) numbers for the range.
8. Calling the Function and Printing the Result
print(perfect_squares(start, end))
perfect_squares(start, end): Calls the function with the user-provided range.
print(): Displays the resulting list of perfect squares.
#source code --> clcoding.com