Python Forum
I'm having a problem with this cube root code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I'm having a problem with this cube root code (/thread-10183.html)



I'm having a problem with this cube root code - Duc311003 - May-16-2018

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")



RE: I'm having a problem with this cube root code - ljmetzger - May-16-2018

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


RE: I'm having a problem with this cube root code - buran - May-16-2018

@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))