We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 3
the program, when executed, will display an error on
the screen (see Figure 6-6).
a
Code and execute
productName = "Chromecast"
productPrice = 30
print("Name: "+productName)
print("Price: "+productPrice)
Typeerrer Traceback
sdpython-input-5-czasazocsgad> in ()
2 productPrice = 30
2 print ("Nam -oducthame)
> 4 print ("Pri roductPrice)
Typeerrer: can only concatena
str (not “int™) to str
Figure 6-6. Error when trying to concatenate
invalid types.
To solve the previous problem, we must convert the
numeric value to type str. The following code shows
how in line 4, we use the str function to convert
the value stored in the variable productPrice to type
sty, and now the concatenation is valid. Figure 6-7
shows the output on the screen of the execution of
the previous code.Code and execute
productName = "Chromecast"
productPrice = 30
print("Name: "+productName)
a
print("Price: "+ str(productPrice))
Name: Chromecast
Price: 30
Figure 6-7. Execution of the previous code.
fe Quick discussion: In Python, it is also
possible to print multiple values and
variables within a single print state-
ment by separating them with commas
“” (as shown in the following code). In
this case, the values separated by com-
mas can be of different types (there is
no need to convert them all to str). We
can see that we do not need to con-
vert productPrice to str. However, in this
book, we will only use concatenation
since repeating this process helps us in-
ternalize the concept of variable typingin Python. This will be very useful for
understanding later concepts.
Code and execute
1. productName = "Chromecast"
2. productPrice = 30
3. print("Name:",productName,"- Price:",product-
Price)
6.5. Exercises
Theoretical exercises
E6.1. What type is each of the following variables?
Note: assume that in line 2, the user enters 59.
Analyze
1. elonAge=51
2. bezosAge = input("Enter age: ")
3. bezosAgeModified = int(bezosAge)
E6.2. What is the purpose of the input function?