为什么这个返回一个额外的none?

2024-04-25 23:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

def hotel_cost(nights):
    return nights * 140

bill = hotel_cost(5)

def add_monthly_interest(balance):
    return balance * (1 + (0.15 / 12))

def make_payment(payment, balance): 
    new_balance2 = balance - payment
    new_balance = add_monthly_interest(new_balance2)
    print "You still owe: " + str(new_balance)

make_payment(100,bill)

为什么会回来

^{pr2}$

是吗?在


Tags: addnewmakereturndefpaymenthotelprint
2条回答

这在@abarnert的帖子的评论中提到过,但是我把它放在了答案的形式中,这样更容易被看到。在

您需要的是让函数返回字符串,然后解释器将该字符串吐回给您:

def make_payment(payment, balance): 
    new_balance2 = balance - payment
    new_balance = add_monthly_interest(new_balance2)
    return "You still owe: " + str(new_balance) # <  Note the return

# Now we change how we call this
print make_payment(100,bill)

# An alternative to the above
message = make_payment(100,bill)
print message

现在,命令行上只显示消息。在

注意

正如您之前编写的代码(省略return语句)一样,python假设您将函数编写为:

^{pr2}$

所有函数都必须返回一个值,由于没有包含return语句,python为您添加了一个值。由于您的交互式shell似乎正在将python函数返回的所有值打印到屏幕上,因此您在调用函数后看到了None。在

它不会返回这个值。它返回None,因为如果没有return语句,任何函数都会返回这个值。在

同时,它会打印出“You still love:607.5”,因为这就是你的打印声明。在

(这里的“it”是指函数调用make_payment(100, bill)。)

我的猜测是,您正在IDE或其他交互会话中运行,该会话打印出每个语句的返回值。因此,您的代码将输出“You still owed:607.5”,然后您的交互式解释器将输出“None”。在

默认的python交互式解释器(如ipython和{}和其他许多)将吞并None返回,而不是打印出来。不管你用的是哪一种,大概都不会。在

相关问题 更多 >