Given a number as input to the program, you have to write a Python to function that takes the input number and returns the square of that particular number.
There are two ways to solve this in Python
- Using the power of operator **
- Using multiplication operator *
Both solutions are just a 4 line python code.
Write A Python Function Square That Takes In One Number And Returns The Square Of That Number
Let’s define a function named square, the function takes and integer number as a input argument and then using the return keyword return the square of a number by multiplying it by number itself
def square(n):
return n * n
In the main program take a variable and ask the user to input a number using the input function and then convert it into an integer type.
Once the user enters the number, use the print function to call the square function by passing the user input number to the function.
number = int(input("Enter a Number : "))
print(f"Square of {number} is {square(number)}")
Complete program
=====================
def square(n):
return n * n
number = int(input("Enter a Number : "))
print(f"Square of {number} is {square(number)}")
Output
==============
Enter a Number : 5
Square of 5 is 25
Output 2
================
Enter a Number : 3
Square of 3 is 9
The above program can also be modified using the double star ** operator, to raise the number to the power off 2.
Complete program
====================
def square(n):
return n ** 2
number = int(input("Enter a Number : "))
print(f"Square of {number} is {square(number)}")
Output
============
Enter a Number : 23
Square of 23 is 529
Output 2
================
Enter a Number : 25
Square of 25 is 625
Conclusion
===============
Try to run the program by yourself by providing the random input number, note down the results.
Comment down below if you have any suggestions to improve the above program or queries related to the above program.
0 Comments