You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数返回NoneType错误原因咨询:《Python3入门指南》示例异常分析

问题分析与解决

根源:return语句缩进错误

你遇到这个TypeError的核心原因,是**get_integer_input函数里的return语句被错误缩进在了while循环内部**(虽然你贴的代码看起来是对的,但实际运行的代码大概率存在这个问题)。

咱们一步步拆解逻辑:

  • 当你第一次输入有效的整数(比如20)时,value_as_string.isnumeric()返回True,while not ...的条件不成立,循环直接跳过。如果return语句在循环里面,函数就没有执行任何return操作,Python中函数默认会返回None。
  • 之后你执行age = int(age),相当于试图把None转换成整数,自然就会抛出TypeError: int() argument must be a string... not 'NoneType'。
  • 而当你先输入非整数(比如Red),程序会进入while循环,此时输入有效整数后,循环内部的return会被触发,函数返回正确的整数值,所以后续代码能正常运行。

修复方案

把return int(value_as_string)放在while循环的外部,和while语句保持同一缩进级别,确保无论第一次输入是否有效,函数都会执行到返回语句:

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要和while对齐,不在循环内部
    return int(value_as_string)

# 注意:函数已经返回int类型,不需要再转一次
age = get_integer_input("Please input your age: ")
print("age is", age)

额外优化建议

  1. 函数内部已经把输入转换成int返回了,所以调用后不需要再执行age = int(age),这一步完全多余,直接用函数返回值即可。
  2. 另外,isnumeric()方法对负数的处理有问题(比如输入-20会被判定为非数字),如果需要支持负整数或者更健壮的输入验证,可以考虑用try-except的方式实现:
def get_integer_input(message):
    while True:
        try:
            value = int(input(message))
            # 可以额外加大于0的判断
            if value <= 0:
                print("The input must be an integer greater than zero.")
                continue
            return value
        except ValueError:
            print("The input must be an integer greater than zero.")

内容的提问来源于stack exchange,提问作者RedHorseMane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:02:27