Of course! Here is a Python function that takes one number as a parameter and returns its square, along with explanations and examples.
The Function
This is the most common and "Pythonic" way to write the function using the exponentiation operator (**).
python
def square(number):
"""
Calculates the square of a given number.
Args:
number (int or float): The number to be squared.
Returns:
int or float: The square of the input number.
"""
return number ** 2
How to Use It
Here are some examples of how you would call this function and use its result.
Example 1: Squaring an integer
python
# Call the function with the number 5
result = square(5)
# Print the result
print(result)
# Output: 25
Example 2: Squaring a floating-point number
python
# You can also use floating-point numbers (numbers with decimals)
result_float = square(10.5)
print(result_float)
# Output: 110.25
Example 3: Using the function directly in a print statement
This example shows a more complete script where you ask the user for a number and then show them the squared result.
python
# Get input from the user
user_input_str = input("Please enter a number to square: ")
# Convert the user's input string to a number (float handles both integers and decimals)
try:
num = float(user_input_str)
# Call the function with the user's number
squared_value = square(num)
# Print a nice, formatted result
print(f"The square of {num} is {squared_value}")
except ValueError:
print("Invalid input. Please enter a valid number.")
Alternative Ways to Write the Function
While number ** 2 is standard, there are other ways to achieve the same result in Python.
1. Using Multiplication
This is a very simple and efficient alternative.
python
def square_multiply(number):
"""Calculates the square using multiplication."""
return number * number
# --- Usage ---
print(square_multiply(8))
# Output: 64
2. Using the pow() built-in function
Python has a built-in function pow(base, exponent) that is perfect for this.
python
def square_pow(number):
"""Calculates the square using the built-in pow() function."""
return pow(number, 2)
# --- Usage ---
print(square_pow(7))
# Output: 49