【发布时间】:2020-10-12 06:46:11
【问题描述】:
用户输入“圆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")
感谢 cmets。我也尝试了另一种方法来解决这个问题。代码是:
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, bl, h = int(s[1]), int(s[2]), int(s[3])
print(f'area={(ul+bl)*h/2}')
else:
print('Wrong input!')
【问题讨论】:
-
欢迎来到 SO。您的代码中有一些问题。 1) 你正在覆盖你的变量
s。 2) 尝试s.split(":")请发布完整的错误回溯。 -
大括号不用于分组,使用括号。
-
@Marichyasana 这里的大括号不用于分组,它们是 f-string 语法的一部分。
-
@Ryo kamili 使用
math.pi而不是 3.14。