Difference in concatenating data in Python 3.7

2

I thank in advance the people who can help me with this query, since I am new to programming.

I am taking a python course and I was practicing the conditionals and the following question arose: Why when concatenating with commas do not give me any error but when I concatenate with the plus sign (+) I get the following error: TypeError: can only concatenate str (not "int") to str

I have read that in Python you can not concatenate different data. If when putting the plus sign the note variable in this way str (note) performs the print but the data converts it to string.

Sorry if the question has no logic or is obvious for those who have experience but do not want to leave empty or doubt.

nombre = "Jean Carlos"
nota = 4

if nota >= 8:
    print("Felicidades" , nombre , " Tu nota es" ,nota , "." , "Eres un excelente alumno")
else:
    print(nombre , "Lamentamos que tu nota se" , nota , "Perdiste el año")
    
asked by Carlos Code 06.12.2018 в 05:09
source

1 answer

3

Starting from this example:

name = "alfred"
edad = 23

print(name,edad)

What results in the following

  

Traceback (most recent call last): File "python", line 4, in    TypeError: must be str, not int

We then obtain that Python needs to concatenate that the values are of the same data type; that is, int with another value int or string with another value string

So if we now do:

name = "alfred"
edad = 23

print(name,edad)

We obtain the following as a result

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

alfred 23

Now we also have the possibility to apply something similar to a casteo de datos that is to say that one of the two values is of the same type as the other, so that if we do the following

name = "alfred"
edad = 23

print(name+' '+str(edad))

We get as a result

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

alfred 23

That is, we pass the value of 23 to the function str() that will cast it to a data type string

With the type method we can read what type of data is, so that in the following script you can see how the variable edad at first is of type int but after the cast becomes type o str

edad = 23
converted = str(edad)

print(type(edad))       //imprime int
print(type(converted))  //imprime str

This is the result

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

<class 'int'>
<class 'str'>
    
answered by 06.12.2018 / 05:38
source