|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想问怎么添加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:
- 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;
复制代码
|
|