如何解决我想在python上计算不同形状的面积
用户输入“圆3.5”或“矩形3 5”或“梯形3 5 7”(由用户决定数量)并输出区域。下面是代码,但无法运行。
s=input("Input the shape and number:")
# for example,# s="rect:5 3"
# s="cir:3.5"
#s="trapz:3 5 7"
cmd,para=s.split(:)
print(f"{cmd}->{para}")
if cmd == 'cir':
r = float(para)
print(f"area={r*r*3.14}")
elif cmd == 'rect':
sw,sh = int(para.split())
print(f"area={sw*sh}")
elif cmd == 'trapz':
ul,bl,h = int(para.split())
print(f"area={(ul+bl)*h/2}")
else:
print("wrong input")
s=input("Input the shape and number:").split()
if s[0]=="cir":
r = float(s[1])
print(f'area={r*r*math.pi}')
elif s[0]=="rect":
sw,sh = int(s[1]),int(s[2])
print(f"area={sw*sh}")
elif s[0]=="trapz":
ul,h = int(s[1]),int(s[2]),int(s[3])
print(f'area={(ul+bl)*h/2}')
else:
print('Wrong input!')
解决方法
您不能仅将int
应用于列表
s=input("Input the shape and number:")
cmd,para=s.split(":")
print(cmd,"->",para)
if cmd=='cir':
r = float(para)
print(f"arear={r*r*3.14}")
elif cmd=='rect':
sw,sh = (float(x) for x in para.split())
print(f"area={sw*sh}")
elif cmd=='trapz':
ul,bl,h = (float(x) for x in para.split())
print(f"area={(ul+bl)*h/2}")
else:
print("wrong input")
,
您的问题有多个。例如,您尝试将多个值传递给int()
和float()
,这些值采用并返回单个值。要将int
应用于列表,可以使用map
函数,否则该函数将不会运行。
我建议您查看尝试运行此代码时收到的错误消息。在学习Python时,这样做是有价值的做法。
,您要输入信息,并在此处将其答案分配给's'变量:
s=input("Input the shape and number:")
然后将s变量的值更改为其他字符串三遍。
s="rect:5:3"
s="cir:3.5"
s="trapz:3 5 7"
这行代码之后,无论用户输入什么,s变量都等于字符串:“ trapz:3 5 7”。
此外,用作'split'参数的冒号必须是字符串。
,您的代码有一些问题。用户提供输入后,您将为分配一个值。我假设这些仅供您参考,所以我将其注释掉。
由于s.split()
会将字符串转换为列表,因此需要确保将列表的一部分分配给正确数量的变量。您不能直接将两个变量分配给一个三元素列表。因此,我使用s.split(':')[0],s.split(':')[1:]
来获取列表的第一个元素,然后获取同一列表的其余元素。
此外,您无法将int()
应用于列表,因为Python不会为您带来太多魔力,因此您需要使用列表推导。
s=input("Input the shape and number:")
# s="rect:5:3"
# s="cir:3.5"
# s="trapz:3 5 7"
cmd,para=s.split(':')[0],s.split(':')[1:]
print(cmd,para)
if cmd=='cir':
r = float(para[0])
print(f"arear={r*r*3.14}")
elif cmd=='rect':
sw,sh =[int(x) for x in para]
print(f"area={sw*sh}")
elif cmd=='trapz':
ul,h = [int(x) for x in para]
print(f"area={(ul+bl)*h/2}")
else:
print("wrong input")
样本输出:
Input the shape and number:rect:5:3
rect -> ['5','3']
area=15
Input the shape and number:cir:3.5
cir -> ['3.5']
arear=38.465
Input the shape and number:trapz:3:5:7
trapz -> ['3','5','7']
area=28.0
,
尝试:
s=input("Input the shape and number:")
s = s.split(':')
cmd,para= s[0],s[1:] # <---- added this
print(cmd,sh =list(map(int,para)) #<---- added this
print(f"area={sw*sh}")
elif cmd=='trapz':
ul,h = list(map(int,para))
print(f"area={(ul+bl)*h/2}")
else:
print("wrong input")
Input the shape and number:trapz:3:5:7
trapz -> ['3','7']
area=28.0
Input the shape and number:rect:3:5
rect -> ['3','5']
area=15
Input the shape and number:cir:4.6
cir -> ['4.6']
arear=66.44239999999999
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。