Почему эта функция Python возвращает ошибку None? - PullRequest
0 голосов
/ 29 апреля 2020

В учебнике «Руководство для начинающих по 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?

Ответы [ 3 ]

0 голосов
/ 29 апреля 2020

Вы поместили return внутри l oop, который никогда не вводится, если вы вводите число, подобное 20. Итак:

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)
        print(value_as_string)

    return int(value_as_string)
age = get_integer_input("Please input your age: ")
age = int(age)
print("age is", age)
0 голосов
/ 29 апреля 2020

Простое исправление:

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)
    print(value_as_string)
    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)
    return int(value_as_string)


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

Добавлено возвращаемое значение сразу после l oop в get_integer_input, так как в противном случае оно фактически ничего не возвращает, потому что value_as_string считается как цифра c при проверке этим параметром while l oop и, следовательно, не ложным, поэтому l oop не запускается никогда, и, поскольку он не видит других операторов по умолчанию, age = get_integer_input("Please input your age: ") возвращает NoneType, и когда он пытается разрешить это в int: age = int(age) выдает ошибку, поскольку вы не можете преобразовать None в пригодное для использования число.

Таким образом, помещение возвращаемого значения вне этого значения, в то время как l oop решает проблему, так как теперь функция is возвращает значение вместо значения по умолчанию none при отсутствии возврата.

0 голосов
/ 29 апреля 2020

Когда вы вводите целое число с первой попытки, вы не вводите время l oop (потому что условие никогда не выполняется), поэтому вы не достигнете return, который находится внутри этого l oop , Вы должны были поставить это return за пределами l oop:

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)
...