如何在Python中添加两个变量并分配给结果变量?
我对python世界非常陌生,请帮助我如何连接str和int对象如何在Python中添加两个变量并分配给结果变量?,python,Python,我对python世界非常陌生,请帮助我如何连接str和int对象 a = 100 b= 200 c = 'Result =' print (c + a + b) 投掷误差 >>> print (c + a + b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' o
a = 100
b= 200
c = 'Result ='
print (c + a + b)
投掷误差
>>> print (c + a + b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
打印(c+a+b)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法连接'str'和'int'对象
I将输出视为,结果=300
提前感谢
a = 100
b = 200
c = 'Result = '
print (c + str(int(a + b)))
更简单
实际上,您可能不需要c
a = 100
b = 200
print ('Result = ', (a + b))
这种编码格式是安全的,因为您可以随时更改字符串变量,并且无需担心输出。要添加两个变量,请使用
c=a+b
。前面已经明确提到,您必须将int
转换为str
,或者像这样使用打印({0}{1}{2})。如果您是新手,请使用格式(c,a,b))
,正确的做法是继续阅读你正在使用的任何教学材料,而不是立即提出问题。这不会产生预期的效果这会产生类似“结果=300”的结果。阿什拉夫不是这样问的吗?太好了。。!!!非常感谢,你能解释一下两者的区别吗。打印(c+str(a)+str(b))并打印(c+str(a+b))以确保完整性:str(int(a+b))
@Rizzit没错
a = 100
b = 200
print ('Result = ', (a + b))
a = 100
b = 200
c = 'Result = '
print("{}{}".format(c,a+b))