Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(name + age) TypeError: can only concatenate str (not "int") to str

huangapple go评论96阅读模式
英文:

Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(name + age) TypeError: can only concatenate str (not "int") to str

问题

我在编写上面的代码时遇到了一个错误,你能帮我吗?

```python
name = 'mahbod'
age = 12
print(name + age)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(name + age)
TypeError: can only concatenate str (not "int") to str
英文:

I was writing the above code when I encountered an error can you help me?

name = &#39;mahbod&#39;
age = 12
print(name + age)
Traceback (most recent call last):
  File &quot;&lt;pyshell#2&gt;&quot;, line 1, in &lt;module&gt;
    print(name + age)
TypeError: can only concatenate str (not &quot;int&quot;) to str

答案1

得分: 1

代码部分不需要翻译。以下是翻译好的内容:

It looks like you want to define two different variables: name and age.
In that case, you need to define each of them on a different line:

name = "mahbod"
age = 12

otherwise, here Python thinks that you are defining name as "Mahbod" age.
In python, you can concatenate strings by separating them with a space, like this:

>>> string = "Hello " "world"
>>> print(string)
Hello world

so that's what Python is trying to do here, except that age is not a string, but a variable that you defined as 12, hence the confusion

英文:

It looks like you want to define two different variables: name and age.
In that case, you need to define each of them on a different line:

name = &quot;mahbod&quot;
age = 12

otherwise, here Python thinks that you are defining name as &quot;Mahbod&quot; age.
In python, you can concatenate strings by separating them with a space, like this:

&gt;&gt;&gt; string = &quot;Hello &quot; &quot;world&quot;
&gt;&gt;&gt; print(string)
Hello world

so that's what Python is trying to do here, except that age is not a string, but a variable that you defined as 12, hence the confusion

huangapple
  • 本文由 发表于 2023年2月23日 21:55:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定