Python,为什么打印无,修复是什么?

时间:2015-06-06 12:12:08

标签: python

当我运行以下代码时,它会打印“无”字样。它应该打印用户输入的金额。为什么要这样做,以及如何解决它?

def amount(thing):
    amnt = int(input('How many ' + thing + ' would you like?'))

bolts_amount = amount('bolts')
print(bolts_amount)

1 个答案:

答案 0 :(得分:2)

您需要return该函数的值,否则默认返回None

def amount(thing):
    amnt = int(input('How many ' + thing + ' would you like?'))
    return amnt

bolts_amount = amount('bolts')
print(bolts_amount)

在函数内部执行amnt = int(input('How many ' + thing + ' would you like?'))不会影响函数之外的结果。您需要return这个值,这样当您调用函数amount()时,它会为您提供一个值来分配给变量bolts_amount