简体   繁体   English

如何在Python中的另一个函数中调用一个函数

[英]How to call a function within another function in Python

As you can see I am trying to do make a currency converter. 如您所见,我正在尝试制作货币转换器。 What I am trying to do is say that if the number "1" is inputted then go to the function 'gbp'. 我要说的是,如果输入数字“ 1”,请转到函数“ gbp”。 It works fine until it gets to where it asks you how much money you want to convert (line 25). 它工作正常,直到到达询问您要转换多少钱的地方(第25行)。 When I type in a value and press enter it comes up with a traceback error, telling me that all of lines 33, 5, and 29 have "unsupported operand type(s) for +: 'float' and 'str'". 当我键入一个值并按Enter时,它会产生一个回溯错误,告诉我第33、5和29行都具有“ +不支持的操作数类型:'float'和'str'”。

This is my code: 这是我的代码:

def start():
print("Hello and welcome to the very limited currency converter!\nIn this converter, the number '1' means Pounds Sterling, number '2' means US Dollars, '3' means Euros and '4' means Japanese Yen.")
From = input("Which currency do you wish to convert from?\n")
if From == ("1"):
    gbp()
    return
elif From == ("2"):
    usd()
    return
elif From == ("3"):
    euro()
    return
elif From == ("4"):
    yen()
    return
else:
    print("That is not a valid input. Please restart the program and input either '1', '2', '3' or '4'!")
return start

def gbp():
gbpTo = input("Which currency are you converting into?\n")
if gbpTo == ("1"):
    print("You are converting Pounds Sterling to Pounds Sterling... there is no conversion needed!")
elif gbpTo == "2":
    num = float(input("Please type in the amount of Pounds Sterling that you wish to convert into US Dollars.\n"))
    calc = num * 1.55
    float(calc)
    calc = round(calc, 2)
    print(num + " Pounds Sterling in US Dollars is $", + calc)
    return
start()

I'd appreciate any help. 我将不胜感激。 Thanks 谢谢

You're trying to add a float and a string. 您正在尝试添加浮点数和字符串。 Python doesn't know which kind of adding you want to do, so you need to convert num and calc to strings before concatenating it to a string: Python不知道您要添加哪种类型,因此您需要先将numcalc转换为字符串,然后再将其连接为字符串:

print(str(num) + " Pounds Sterling in US Dollars is $" + str(calc))

Instead of 代替

print(num + " Pounds Sterling in US Dollars is $", + calc)

do

print("%f Pounds Sterling in US Dollars is $ %f" % (num, calc))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM