0

Here is the code :

PI = 3.14
radius = float(input('Please Enter the Radius of a Sphere: '))

sa = 4 * PI * radius * radius
Volume = (4 / 3) * PI * radius ** 3

print("\n The Surface area of a Sphere = %.2f" %sa)
print("\n The Volume of a Sphere = %.2f" %Volume)

Its says above please enter the radius of a sphere. How could I make it not error code if I enter a string because when I do it says this :

Traceback (most recent call last):
  File "D:/Gary/Test2/Euan_4.py", line 2, in <module>
    radius = float(input('Please Enter the Radius of a Sphere: '))
ValueError: could not convert string to float: 'rtt'

How could this be fixed.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
eun ason
  • 29
  • 1
  • 5

2 Answers2

0
def take_input():
  try:
    radius = float(input('Please Enter the Radius of a Sphere: '))
    return radius
  except:
    print('please enter a float')
    return take_input()




radius = take_input()

this will retry till user enters the right input.

PYA
  • 8,096
  • 3
  • 21
  • 38
  • have u got a remedy for when i enter a 'y' it would error straight away @pyjg could u help me fix this – eun ason Aug 28 '17 at 18:17
  • what do you mean? if you enter 'y' and hit return it will show the error and ask for input again – PYA Aug 28 '17 at 18:18
  • no it wont ask for input itll just say 'Traceback (most recent call last): File "D:/Gary/Test2/Euan_4.py", line 2, in radius = float(input('Please Enter the Radius of a Sphere: ')) ValueError: could not convert string to float: 'y' @pyjg like i want it to , if i enter a string , to print 'thats a string try again ' and not error – eun ason Aug 28 '17 at 18:21
  • I do not see how that is happening. https://repl.it/K3wL check this link – PYA Aug 28 '17 at 18:45
0

You could use try.. except

try: 
    PI = 3.14
    radius = float(input('Please Enter the Radius of a Sphere: '))

    sa = 4 * PI * radius * radius
    Volume = (4 / 3) * PI * radius ** 3

    print("\n The Surface area of a Sphere = %.2f" %sa)
    print("\n The Volume of a Sphere = %.2f" %Volume)
except Exception as e:
    print("error : " +str(e))
    print("make sure to provide an float as input")

Here's the output when testing with a number:

Please Enter the Radius of a Sphere: 111

 The Surface area of a Sphere = 154751.76

 The Volume of a Sphere = 4294361.34

Here's the output when testing with a string:

Please Enter the Radius of a Sphere: rtt
error : name 'rtt' is not defined
make sure to provide an float as input
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
  • i use this and its got red lines next to 'except Exception as e: print("eorr : " +str(e))' and ' PI = 3.14 radius' y is this @MedAli – eun ason Aug 28 '17 at 18:22
  • @eunason I tried it on my system, I am editing the answer to share what I am getting as ouput. Could you share you python version ? – Mohamed Ali JAMAOUI Aug 28 '17 at 18:45