我试图在一个程序中使用两个函数来制作一个货币兑换器,但由于某些原因,我的程序要么得到这个错误。
line 23, in Input1
print(amount+"Won equals to "+totalamount+" USD")
TypeError: unsupported operand type(s) for +: 'float' and 'str'
或者在输入 "选项 "和 "金额 "后没有打印任何东西。这是我的程序。
print("Please choose which currency you want to convert:")
print("A - Korean Won to US Dollar (Exchange Rate: 0.000905)")
print("B - Korean Won to Euro (Exchange Rate: 0.000807350908)")
print("C - Korean Won to Japanese Yen (Exchange Rate: 0.0919061643)")
print("D - Korean Won to Chinese RMB (Exchange Rate: 0.00603703605)")
print("E - Quit")
usd = 0.000905
eur = 0.000807350908
yen = 0.0919061643
rmb = 0.00603703605
def main():
option =input("Enter your option: ")
if option== "E":
exit()
amount =float(input("Enter the amoutn in Korean Won: "))
Input1(option, amount)
def Input1(option,amount):
if option == "A":
totalamount = (amount * usd)
print(amount+"Won equals to "+totalamount+" USD")
elif option== "B":
totalamount = (amount * eur)
print (amount+"Won equals to "+totalamount+" Euro")
elif option== "C":
totalamount = (amount * yen)
print (amount+"Won equals to "+totalamount+" Yen")
elif option== "D":
totalamount = (amount * rmb)
print (amount+"Won equals to "+totalamount+" Chinese RMB")
else:
print("You entered an invalid input.")
return option,amount
main()
你们能不能给我一些提示来解决我的程序?我还在学习python,任何帮助将是非常感激的。非常感谢您
你只需要把当前浮动的金额和totalamount变量打成字符串就可以了
print(str(amount)+"Won equals to "+str(totalamount)+" USD")
或者使用你使用的格式功能
print("{} Won equals to {} USD ".format(amount, totalamount))
而且我认为格式功能是更好的选择
你必须转换 amount
和 totalamount
的字符串,然后再将其用于 print()
作为带+的字符串。你可以使用 str()
方法。
print(str(amount)+"Won equals to "+str(totalamount)+" USD")
使用f-string代替字符串连接,它将为你处理转换。
print(f"{amount} won equals to {totalamount} USD")
如果你真的想自己做转换,它看起来会像这样。
print(str(amount) + "Won equals to " + str(totalamount) + " USD")
(编辑) 为了回答评论中的问题,把你的... main()
功能,以。
def main():
while True:
option = input("Enter your option: ")
if option== "E":
break
amount = float(input("Enter the amount in Korean Won: "))
Input1(option, amount)