27.5k views
4 votes
Instructions

Write the code to input a number and print the square root. Use the absolute value function to make sure that if the user enters a
negative number, the program does not crash.

1 Answer

6 votes

Answer:

*** Python Code ***

from math import sqrt

def squareRoot(x):

print(sqrt(abs(x)))

squareRoot(float(input("Square-root of this number: ")))

*** Sample Input ***

Square-root of this number: 4

*** Sample Output ***

2.0

Step-by-step explanation:

For this problem, we will simply use the python built-in methods for finding the square root and taking the absolute value of a number.

Line 1: from math import sqrt

This line of code imports the square root method from the math module so we can compute the square root of our number

Line 2: def squareRoot(x):

This line of code is a function definition of a method we are creating called "sqareRoot" in which it takes a single argument x

Line 3: print(sqrt(abs(x)))

This line of code takes the absolute value of the function argument x, takes the square root of that number, and then prints the result to the console

Line 4: squareRoot(float(input("Square-root of this number: ")))

This line of code takes in a user input number, converts the string to a float, and then passes the number as the argument to our user defined function squareRoot

Cheers.

User Sparga
by
5.6k points