Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to calculate the square and cube of a number - Python Program

Example 1 :

def square_and_cube(num): """Return square and cube of num.""" return num**2, num**3 sq, cb = square_and_cube(4) print("Square:", sq, "Cube:", cb)

Output

 
OUTPUT  :
Square: 16 Cube: 64

Example 2 : Advanced Program

def calculate_square_and_cube(number): """ Calculates the square and cube of a given number and prints the results. Args: number (int or float): The number for which to calculate the square and cube. """ square = number ** 2 cube = number ** 3 print(f"The square of {number} is: {square}") print(f"The cube of {number} is: {cube}") # Example Usage: # Get input from the user try: user_input = float(input("Enter a number: ")) calculate_square_and_cube(user_input) except ValueError: print("Invalid input. Please enter a valid number.") print("\nAnother example with a pre-defined number:") calculate_square_and_cube(5)

Output

 
OUTPUT  :
Enter a number: 10
The square of 10.0 is: 100.0
The cube of 10.0 is: 1000.0

Another example with a pre-defined number:
The square of 5 is: 25
The cube of 5 is: 125

Explanation:

calculate_square_and_cube(number) Function:

  • This function is defined using the defkeyword and takes one argument, number, which represents the value for which the square and cube will be calculated.
  • Inside the function, number ** 2 calculates the square of the input number, and number ** 3 calculates its cube. The ** operator in Python performs exponentiation.
  • The results are stored in variables square and cube, respectively.
  • Finally, the print() statements display the original number, its calculated square, and its calculated cube in a user-friendly format using f-strings for easy formatting.