Python Forum
I'm having a problem with this cube root code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I'm having a problem with this cube root code
#1
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")
Reply
#2
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
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply
#3
@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))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  keyboard module; must be root problem philipbergwerf 2 19,391 Apr-04-2021, 11:40 AM
Last Post: philipbergwerf
  unable to pass a input after changing the user from root to non root using python avinash 3 3,251 Apr-08-2019, 10:05 AM
Last Post: avinash
  Square and Cube roots. jarrod0987 2 5,530 Apr-13-2018, 09:30 PM
Last Post: casevh
  "³" math cube symbol encoding Ragnar 5 9,762 Mar-09-2018, 04:23 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020