Python编写符合要求的函数时出现TypeError: NoneType相加报错如何解决?
报错触发逻辑
出现TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'的核心原因是Python函数未显式编写return语句时,默认返回None,加上参数传递逻辑缺失,形成连锁问题:
score_input()函数:完成了输入转整数的操作,但没有将转换后的分数通过return返回,导致后续赋值得到的score_a、score_b均为None,两个None做加法操作时直接触发类型报错find_avg()函数:没有定义接收两个分数的形参,直接读取全局作用域的变量;即使函数内完成了平均分计算,也没有将计算结果通过return返回,最终得到的avg值为Noneoutput()函数:没有定义接收姓名、平均分的形参,直接读取全局作用域变量,虽能读到值,但不符合“函数接收入参、独立完成对应逻辑”的编码规则
合规修正代码
# A function that prompts the user for a name and returns it to the # calling statement. def getName(): name = input("Please enter your name: ") return name # A function that prompts the user for a score and returns it to the # calling statement. def score_input(): score = int(input("Enter your score: ")) return score # A function that receives two numbers and returns the average of those # two values to the calling statement. def find_avg(score1, score2): return (score1 + score2) / 2 # A function that receives a string and a number (the name and the # average score) and prints it out on the screen in the appropriate format. def output(user_name, user_avg): print("Hi, {}. Your average score is {}".format(user_name, user_avg)) ############################################################################# # prompt for name name = getName() # prompt for two scores score_a = score_input() score_b = score_input() # calculate the average,将两个分数作为实参传入计算函数 avg = find_avg(score_a, score_b) # display the final output,将姓名、平均分作为实参传入打印函数 output(name, avg)
修正后的运行逻辑说明
- 所有需要向外传递数据的环节,都通过return明确返回值,不会再生成None类型的默认返回值
- 所有需要外部数据的函数,都通过形参接收调用方传入的实参,不依赖全局变量跨作用域读取,完全符合模块化函数的设计要求
内容的提问来源于stack exchange,提问作者Nebuloe
相关产品推荐
相关产品推荐

