【问题标题】:Python, why does this print None, and what is the fix? [duplicate]Python,为什么这会打印无,修复方法是什么? [复制]
【发布时间】:2015-08-21 08:35:12
【问题描述】:

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

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    你需要从函数中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

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2020-01-11
      • 2019-02-09
      相关资源
      最近更新 更多