将print(input())赋值给变量为何报错?变量值为何为None?
问题分析与修复方案
错误根源
你遇到的TypeError是因为将print()的返回值赋值给了name1和name2。print()函数仅负责向控制台输出内容,不会返回任何有效数据,Python中这类仅执行操作无返回值的函数默认返回None。这导致name1和name2的取值都是None,而None类型无法用+运算符拼接,因此触发错误。
为什么print()返回None
Python函数如果没有显式用return语句返回值,就会默认返回None。print()属于“执行动作但不产生可复用结果”的函数,它只负责把内容打印到屏幕,不会把输入的字符串返回给变量,所以name1 = print(input(...))这种写法里,name1拿到的只能是None。
修复后的代码
只需去掉赋值语句中的print(),直接用input()获取用户输入即可(input()本身会自动输出提示文本):
name1 = input("please enter name1: ") name2 = input("please enter name2: ") combined_names = name1 + name2 lower_names = combined_names.lower() t = lower_names.count("t") r = lower_names.count("r") u = lower_names.count("u") e = lower_names.count("e") first_digit = t + r + u + e l = lower_names.count("l") o = lower_names.count("o") v = lower_names.count("v") e = lower_names.count("e") second_digit = l + o + v + e score = int(str(first_digit) + str(second_digit)) if score < 10 or score > 90: print(f"your score is {score}, you go together like coke and mentos.") elif 40 <= score <= 50: print(f"your score is {score}, you are alright together.") else: print(f"your score is {score}.")
补充说明
input(prompt)函数的prompt参数就是用来显示输入提示的,执行时会自动把提示文本输出到控制台,不需要额外调用print()。比如input("please enter name1: ")运行时,控制台会显示提示并等待用户输入,输入的字符串会直接作为返回值赋值给变量。
内容的提问来源于stack exchange,提问作者YGY
相关产品推荐
相关产品推荐

