【发布时间】:2020-04-29 10:03:10
【问题描述】:
在教科书 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”吗?
【问题讨论】:
-
你确定书中的函数实际上没有
return去凹层吗? (例如 - 它实际上不在while循环本身中......)