[Type C] Working with Functions – Chapter 3 Sumita Arora

|
Table of Contents

6. Write a function named nthRoot() that receives two parameters x and n and returns the nth root of x, i.e., x^(1/n). The default value of n is 2.

Short Answer: The function nthRoot() will calculate the nth root of a number. It takes two parameters, x and n, where x is the number and n is the root. If n is not provided, it defaults to 2.

Python
def nthRoot(x, n=2):
    return x ** (1/n)

# Test
print(nthRoot(16))  # 4.0 (Default value of n is 2)
print(nthRoot(27, 3))  # 3.0

Explanation:

  • The function nthRoot calculates the nth root of a number using the exponentiation operator **.
  • It takes two parameters, x (the number) and n (the root), with n defaulting to 2.
  • Test cases demonstrate how to use the function with both default and custom values for n.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *