Python 添加变量中的两个数字

Python 添加变量中的两个数字,python,concatenation,Python,Concatenation,我刚开始使用Python3,现在使用的是命令shell。为什么下面的代码会出现异常 name = input("whats your name: ") age = input("what is your age: ") work = input("how long will you be working: ") print("Good luck " + name + " you will be " + int(age) + int(work) + " years old") Pytho

我刚开始使用Python3,现在使用的是命令shell。为什么下面的代码会出现异常

 name = input("whats your name: ")
 age = input("what is your age: ")
 work = input("how long will you be working: ")
 print("Good luck " + name + " you will be " + int(age) + int(work) + " years old")
Python调试器生成的错误应为str vs int.

请尝试以下操作:

print("Good luck " + name + " you will be " + str(int(age)) + int(work)) + " years old")

很可能是因为您同时连接字符串和添加int。将它们加在一起,然后转换为字符串,然后再转换为concatitate。

理想情况下,您可以通过intage将str转换为int,然后再次尝试将字符串与整数连接起来。默认情况下,输入以字符串形式获取数据

请避免使用int转换。此外,如果需要,请检查typevar并尝试连接。

问题是字符串+整数无法正常工作。相反,我们需要在方法中转换回字符串

但不要这样写字符串。正如您所看到的,它非常容易出错。相反,请使用字符串格式

print("Good luck {} you will be {} years old".format(name, int(age) + int(work)))
在python 3.6中甚至更好

print(f"Good luck {name} you will be {int(age) + int(work)} years old")

@FHTMitchell,整数转换没有问题,实际上年龄应该是整数,也可以。但是,问题在于字符串连接。如果要转换为“int”,则必须再次转换为“str”,以便与其他字符串连接。希望您能理解。您说过请避免使用int转换为什么?就您的逻辑而言,转换为int没有问题。但重点是连接字符串和字符串,而不是字符串和int。。。非常有效谢谢你的切换语法。