Python3命令行运行代码出现类型错误,请求异常原因解析
问题原因分析与解决方案
嘿,这个问题我刚入门Python的时候也栽过!让我给你掰扯清楚为啥会报错~
错误核心原因
你遇到的should be str vs int错误,本质是Python不允许直接用+运算符把字符串(str)和整数(int)拼接在一起。
具体到你的代码里:
- 所有
input()函数返回的内容都是字符串类型——哪怕你输入的是数字,比如输入25,age变量存的其实是字符串"25",不是整数25; - 你把
age和work转成整数int(age)、int(work)后,这两个变量就变成了整数类型,但你紧接着试图把它们和前面的字符串(比如"Good luck " + name + " you will be ")用+连起来,这种跨类型的拼接操作Python是不允许的,所以直接抛出了类型不匹配的错误。
修正方案(几种常用写法)
方法1:先计算总和再转字符串拼接
先把输入的年龄和工作时长转成整数,计算总和后再转成字符串,就能和其他字符串正常拼接了:
name = input("whats your name: ") age = int(input("what is your age: ")) # 直接把输入转成整数 work = int(input("how long will you be working: ")) total_age = age + work print("Good luck " + name + " you will be " + str(total_age) + " years old")
方法2:用f-string(Python3.6+推荐,最简洁)
f-string是Python3.6以后推出的格式化语法,直接在字符串里嵌入变量或表达式,自动处理类型转换,写起来超省心:
name = input("whats your name: ") age = int(input("what is your age: ")) work = int(input("how long will you be working: ")) print(f"Good luck {name} you will be {age + work} years old")
方法3:用str.format()方法
这是Python3.6之前常用的格式化方式,兼容性更好:
name = input("whats your name: ") age = int(input("what is your age: ")) work = int(input("how long will you be working: ")) print("Good luck {} you will be {} years old".format(name, age + work))
内容的提问来源于stack exchange,提问作者On the path for perfection
相关产品推荐
相关产品推荐

