5 回答

TA貢獻1871條經驗 獲得超8個贊
你不能只申請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")

TA貢獻1794條經驗 獲得超7個贊
您的代碼有一些問題。您在用戶提供輸入后為 s 分配一個值。我假設這些僅供您參考,所以我將它們注釋掉了。
由于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, bl, 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

TA貢獻1789條經驗 獲得超8個贊
你的問題是多重的。例如,您嘗試將多個值傳遞給int()
and float()
,它接受并返回單個值。要應用于int
列表,您可以使用該map
函數,否則它將無法運行。
我建議您查看嘗試運行此代碼時收到的錯誤消息。這是學習 Python 時非常有價值的實踐。

TA貢獻1784條經驗 獲得超7個贊
嘗試:
s=input("Input the shape and number:")
s = s.split(':')
cmd, para= s[0], s[1:] # <---- added this
print(cmd,"->",para)
if cmd=='cir':
r = float(para[0])
print(f"arear={r*r*3.14}")
elif cmd=='rect':
sw, sh =list(map(int, para)) #<---- added this
print(f"area={sw*sh}")
elif cmd=='trapz':
ul, bl, 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', '5', '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

TA貢獻2051條經驗 獲得超10個贊
您要求輸入并將其答案分配給此處的 '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”參數的冒號必須是字符串。
添加回答
舉報