返回值在Python 3中不起作用

时间:2016-01-29 14:32:47

标签: python return

似乎我无法将函数中的值传递给另一个函数,即使我在第一个函数中添加了return语句。

这是我的代码:

price=0
TotalPrice=0

def SumPrice(price,TotalPrice):
    if cup_cone=="cup":
        price=(price+(mass/10)*0.59)*TotalSet
    else:
        if cone_size=="small":
            price=(price+2)*TotalSet
        else:
            if cone_size=="medium":
                price=(price+3)*TotalSet
            else:
                price=(price+4)*TotalSet

    if Member_Ans=="yes":
        TotalPrice=TotalPrice+price*0.90

    print(price,TotalPrice)
    return (price)
    return (TotalPrice)

def PrintDetails(price,TotalPrice,Balance):
    SumPrice(price,TotalPrice)
    if Member_Ans=="yes":
        print("Member ID: ", loginID, " (" , Username, ")")

    for element in range (len(UserFlavor)):
        print (UserFlavor[element], "--- ", UserFlavorPercentage[element], "%")

    print ("Total set = ", TotalSet)
    print ("Total price = RM %.2f" % (price))
    if Member_Ans=="yes":
        print ("Price after 10% discount = RM %.2f" %  (TotalPrice))

    while True:
        Payment=int(input("Please enter your payment: "))
        if Payment<TotalPrice:
            print("Not enough payment.")
        if Payment >= TotalPrice:
            break

    Balance=Balance+(Payment-TotalPrice)
    print(Balance)

PrintDetails(price,TotalPrice,Balance)

当我尝试打印priceTotalPrice时,会打印0,为什么?

2 个答案:

答案 0 :(得分:3)

你试图使用return两次,这是不允许的(你的功能会在它到达第一个return声明后立即结束,使另一个无效)。 但是,您可以在一个语句中返回两个值:

return (price, TotalPrice)

然后将值分配给元组或您想要的任何其他内容:

my_tuple = SumPrice(a, b)

var1, var2 = SumPrice(a, b)

答案 1 :(得分:0)

第一个函数的第二个return语句无法访问! btw尝试不在代码中使用全局变量,而是访问第一个函数的返回值。

def SumPrice():
    price = 0
    TotalPrice = 0
    if cup_cone=="cup":
        price=(price+(mass/10)*0.59)*TotalSet
    else:
        if cone_size=="small":
            price=(price+2)*TotalSet
        else:
            if cone_size=="medium":
                price=(price+3)*TotalSet
            else:
                price=(price+4)*TotalSet

    if Member_Ans=="yes":
        TotalPrice=TotalPrice+price*0.90

    return price, TotalPrice

def PrintDetails():
    price, TotalPrice = SumPrice()
    if Member_Ans=="yes":
        print("Member ID: ", loginID, " (" , Username, ")")

    for element in range (len(UserFlavor)):
        print (UserFlavor[element], "--- ", UserFlavorPercentage[element], "%")

    print ("Total set = ", TotalSet)
    print ("Total price = RM %.2f" % (price))
    if Member_Ans=="yes":
        print ("Price after 10%% discount = RM %.2f" %  (TotalPrice))

    while True:
        Payment=int(input("Please enter your payment: "))
        if Payment<TotalPrice:
            print("Not enough payment.")
        if Payment >= TotalPrice:
            break

    Balance=Balance+(Payment-TotalPrice)
    print(Balance)

PrintDetails()