python - 为什么这个 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”吗?
解决方案
当您在第一次尝试时输入一个整数时,您不会进入 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)
推荐阅读
- javascript - base64-jpeg 转换为 base64-png
- interface - F# 接口语法用 byref 返回的对象(或元组)声明函数,如 Int32.TryParse
- jquery - 使用 Thymaleaf 和数据库抛出异常的动态下拉菜单
- ios - CFStreamCreatePairWithSocketToHost - 如何处理网络断开连接?
- c++ - 尝试使用 winbgi 显示文本时出现编译器错误
- python - 将字典内容插入字符串以提取查询计划
- php - 如何使用 html select 方法和 php 在 psql 数据库上添加全名?
- python - 如何按说话者姓名汇总时间戳列表 v.2
- python - TypeError:列表索引必须是整数或切片,而不是 NoneType
- python - 嵌套循环中的 Tkinter 画布文本更新