Python报错:unsupported operand type(s) for +: 'set' and 'int' 求助
问题解决:类型错误(set与int无法相加)
错误原因
你的代码报错unsupported operand type(s) for +: 'set' and 'int',核心问题在这一行:
age_second = int({age} + 1)
{age}会创建一个集合(set),集合类型无法和整数1执行加法运算,直接触发类型不匹配错误。- 另外,
input()函数返回的是字符串类型,即使不用集合包裹,直接对字符串age做加法也会出错。
修正后的代码
namename = input("What is your name? ") print(f"Hello {namename}") age = input("How old are you? ") # 先把输入的字符串转成整数,再执行加1操作 age_second = int(age) + 1 print(f"Happy birthday {namename}! Your age turns from {age} to {age_second}")
关键修正点
- 先用
int(age)将用户输入的字符串类型年龄转换为整数类型,再执行+1运算,确保数值操作合法。 - 移除错误的
{age}写法,避免无意创建集合导致类型冲突。
内容的提问来源于stack exchange,提问作者user1916853
相关产品推荐
相关产品推荐

