如何用Python使單位米轉(zhuǎn)換為厘米?
1、新建一個(gè)空白的Python文檔。
2、首先初步輸入代碼要求計(jì)算機(jī)提示用戶輸入數(shù)字,并且會(huì)自動(dòng)轉(zhuǎn)換為里面。
但是這個(gè)是錯(cuò)誤的,因?yàn)閙etres * 100不是字符串。
metres = input("Please enter the metres that you want to transfer into centimetres:")
print(metres + "m" + "=" + metres * 100 + "cm")
3、加了STR后,還是錯(cuò)誤,因?yàn)镸ETRES是數(shù)字,數(shù)字要和數(shù)字相乘。
metres = input("Please enter the metres that you want to transfer into centimetres:")
print(metres + "m" + "=" + str(metres * 100) + "cm")
4、metres = input("Please enter the metres that you want to transfer into centimetres:")
print(metres + "m" + "=" + str(float(metres) * 100) + "cm")
這個(gè)才是正確的,可以鍵入數(shù)字檢查是否可以執(zhí)行。
5、為了讓程序觀看方便,定義變量cm。
metres = input("Please enter the metres that you want to transfer into centimetres:")
cm = float(metres) * 100
print(metres + " m " + " = " + str(cm) + " cm "
6、也可以用.format(),這樣修改起來(lái)會(huì)非常方便。
metres = input("Please enter the metres that you want to transfer into centimetres:")
cm = float(metres) * 100
print("{} m = {} cm" .format(metres, cm))