首页 > 解决方案 > 为什么这个 Python 函数返回 None 错误?

问题描述

在教科书 A Beginner's Guide to Python 3 中,第 11 章中有一个函数的示例。程序是:

def get_integer_input(message):
    """
    This function will display the message to the user
    and request that they input an integer.

    If the user enters something that is not a number
    then the input will be rejected
    and an error message will be displayed.

    The user will then be asked to try again."""

    value_as_string = input(message)
    while not value_as_string.isnumeric():
        print("The input must be an integer greater than zero.")
        value_as_string = input(message)
        return int(value_as_string)


age = get_integer_input("Please input your age: ")
age = int(age)
print("age is", age)`

根据教科书,输出应该是:

Please input your age: 21
age is 21

但我得到:

Please input your age: 20

Traceback (most recent call last):
  File "/Users/RedHorseMain/Documents/myPythonScripts/A Beginners Guide to Python 3/6.10.3 getAge.py", line 20, in <module>
    age = int(age)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

但是,如果我首先输入一个字符串而不是整数,该函数应该防止的错误,它可以工作:

Please input your age: Red

The input must be an integer greater than zero.

Please input your age: 21

age is 21

有人可以解释为什么该函数返回“NoneType”吗?

标签: pythonfunctionnonetype

解决方案


当您在第一次尝试时输入一个整数时,您不会进入 while 循环(因为条件永远不会满足),因此您不会到达return该循环内的哪个。你应该把它return放在循环之外:

def get_integer_input(message):
    value_as_string = input(message)
    while not value_as_string.isnumeric():
        print("The input must be an integer greater than zero.")
        value_as_string = input(message)
    return int(value_as_string)

推荐阅读