Python Forum

Full Version: I'm having a problem with this cube root code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made this cube root code,but it didn't work for negative numbers. It always print "No cube roots" even though types of negative numbers are either float or int.
Here's my code:
a = input()
if type(a) == float or type(a) == int:
    if a > 0 or a == 0:
        print (round(float(a**(1/3)),15))
    else:
        a = abs(a)
        b = round(float(a**(1/3)),15)
        print (b * -1)
else:
    print ("No cube roots")
input() always returns a type 'str'.

You can try something like:
import math

try:
    a = input("Enter a number for cube root calculation:  ")
    a = float(a)
    mysign = math.copysign(1, a)
    b = mysign * round(float(abs(a)**(1/3)),15)
    print("The cube root of {} is {}".format(a, b))

except:
    print ("No cube roots because '{}' is NOT a number.".format(a))
Lewis
@Duc311003
as @lzmetzger already said input will return str, so you need to convert it to float/int before comparing with 0
while True:
    try:
        a = float(input('Enter a number:'))
        break
    except ValueError:
        print ("Not a valid input")
if a >= 0:
    print(round(a**(1/3),15))
else:
    print (-1*round(abs(a)**(1/3),15))