Skip to main content
 首页 » 编程设计

python之我在 python 上写了一个货币转换器,它说 'money' 没有定义。这发生在最后的乘法中

2025年05月04日7cyq1162

usd = 2 
yen = 1000 
gbp = 1.7 
eur = 0.75 
 
def again(): 
    choice = False 
    while choice == False: 
        money = input("please enter an amount ") 
    try: 
        int(money) 
    except ValueError: 
        print("inavlid: numbers only") 
        choice == False 
    else: 
        money = int(money) 
        if money >= 1000: 
            confirm = input("are you sure y / n").lower() 
            if confirm == "y": 
                transfer() 
            elif confirm == "n": 
                again() 
            elif confirm != "y" or choice != "n": 
                print("invalid options") 
                yn() 
        else: 
            transfer() 
def xe1(): 
    xe = input("do you want currency rates set on this program(yes) or\ndo you want to make your own currency amounts(no)\n") 
    if xe == 'yes': 
        print ("you have got from ", (money), c, "to ", ((money)/c1*ac1),ac) 
        quit() 
    elif xe == 'no': 
        er = (float(input("what is the exchange rate "))) 
        print ("you have got from ", (money), c, "to ", ((money)*er), ac) 
        quit() 
    else: 
        xe1() 

请您参考如下方法:

money 变量确实没有在 xe1 中定义,因为它的范围仅限于 again() 函数。在更好的实现中,您可以将钱作为参数传递给这两个函数,如下所示:

usd = 2 
yen = 1000 
gbp = 1.7 
eur = 0.75 
 
def again(money): 
    choice = False 
    while choice == False: 
        money = input("please enter an amount ") 
    try: 
        int(money) 
    except ValueError: 
        print("inavlid: numbers only") 
        choice == False 
    else: 
        money = int(money) 
        if money >= 1000: 
            confirm = input("are you sure y / n").lower() 
            if confirm == "y": 
                transfer() 
            elif confirm == "n": 
                again(money) 
            elif confirm != "y" or choice != "n": 
                print("invalid options") 
                yn() 
        else: 
            transfer() 
def xe1(money): 
    xe = input("do you want currency rates set on this program(yes) or\ndo you want to make your own currency amounts(no)\n") 
    if xe == 'yes': 
        print ("you have got from ", (money), c, "to ", ((money)/c1*ac1),ac) 
        quit() 
    elif xe == 'no': 
        er = (float(input("what is the exchange rate "))) 
        print ("you have got from ", (money), c, "to ", ((money)*er), ac) 
        quit() 
    else: 
        xe1(money)