求助!
想问怎么添加raise进去呀?谢谢!!!编写一个函数get_volume(radius,height),该函数将圆柱的半径和高度作为参数,并返回圆柱的体积。将结果四舍五入到最接近的整数。函数应验证值的类型,半径的值和高度的值。
该函数应返回“ERROR: Radius must be positive.”如果半径为负,则返回“ERROR: Height must be positive.” 如果高度为负,则如果两者均为负,则返回“ERROR: Height and radius must be positive”。
当两个参数中的任何一个为0时,该函数都应返回“ERROR: Not a cylinder” 圆柱体的体积由以下公式给出:math.pi*(r^2)*h
注意:您*必须*在解决方案中使用“ try ... except”语法和“ raise”
这个分别是Test 和 Result
print(get_volume(10, 2))
628
print(get_volume(-10, 2))
ERROR: Radius must be positive.
print(get_volume(10, -2))
ERROR: Height must be positive.
print(get_volume(-10, -2))
ERROR: Height and radius must be positive.
print(get_volume(10, 0))
ERROR: Not a cylinder.
print(get_volume('ten', 2))
ERROR: Invalid input.
import math
def get_volume(radius,height):
try:
V=round(math.pi*radius*radius*height);
except:
return "ERROR: Invalid input.";
if(radius<0 and height<0):
return "ERROR: Height and radius must be positive.";
elif(radius<0):
return "ERROR: Radius must be positive.";
elif(height<0):
return "ERROR: Height must be positive.";
elif(radius==0 or height==0):
return "ERROR: Not a cylinder.";
return V; import math
def get_volume(radius,height):
try:
V=round(math.pi*radius*radius*height);
except:
raise TypeError("ERROR: Invalid input.");
if(radius<0 and height<0):
raise ValueError("ERROR: Height and radius must be positive.");
elif(radius<0):
raise ValueError("ERROR: Radius must be positive.");
elif(height<0):
raise ValueError("ERROR: Height must be positive.");
elif(radius==0 or height==0):
raise ValueError("ERROR: Not a cylinder.");
return V; zltzlt 发表于 2020-8-14 18:06
但是这样改的话后面的test就出问题了 ~有点不太对 MIQIWEI 发表于 2020-8-14 18:13
但是这样改的话后面的test就出问题了 ~有点不太对
这样捏?
import math
def get_volume(radius,height):
try:
V=round(math.pi*radius*radius*height);
except:
return "ERROR: Invalid input.";
try:
raise Exception
except:
pass
if(radius<0 and height<0):
return "ERROR: Height and radius must be positive.";
elif(radius<0):
return "ERROR: Radius must be positive.";
elif(height<0):
return "ERROR: Height must be positive.";
elif(radius==0 or height==0):
return "ERROR: Not a cylinder.";
return V; zltzlt 发表于 2020-8-14 18:14
这样捏?
对啦!谢谢大佬!
页:
[1]