以下是代码:
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)
上面说please enter the radius of a sphere
。如果我输入一个字符串,我怎么能使它不是错误代码因为当我这样做时说:
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'
如何解决这个问题。
答案 0 :(得分: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()
这将重试,直到用户输入正确的输入。
答案 1 :(得分:0)
您可以使用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")
这是使用数字进行测试时的输出:
Please Enter the Radius of a Sphere: 111
The Surface area of a Sphere = 154751.76
The Volume of a Sphere = 4294361.34
这是使用字符串进行测试时的输出:
Please Enter the Radius of a Sphere: rtt
error : name 'rtt' is not defined
make sure to provide an float as input