简体   繁体   中英

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'. It works fine until it gets to where it asks you how much money you want to convert (line 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'".

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:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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