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
an int value), print its contents, then modify its
value (to a float value), and print its contents again.
Code and execute
productPrice = 150
print(productPrice)
productPrice = 250.5
a
print(productPrice)
Figure 5-6 shows what happens internally in the
computer’s memory. When line 1 is executed, the
variable productPrice is created with a value of 150
and an int type. Then, line 3 is executed, its value
is modified to 250.5, which also changes its type to
float.
Line 1 Line 3
450 280.5
Figure 5-6. Modifying the value and type of a variable.fe Quick discussion: Recognizing that
variables in Python handle different
types will help us better understand
how Python works and our different
possibilities for using those variables.
Other programming languages have
stricter typing (for example, Java). In
Java, an int variable could not be modi-
fied to a float number (it could only be
modified to another int number).
Reusing variables to define new variables
In many programming languages, it is possible to
create or modify variables based on the values
of previously created variables. The following code
shows how: (i) we create a variable IuisAge with a
value of 10, (ii) we create a variable JawraAge with a
value of 20, (iii) we create a variable sum that will
be equal to the value contained in the variable Iuis-
Age plus the value contained in the variable lauraAge
(which is 30), (iv) we create a variable average thatwill be equal to the variable sum divided by 2, and (v)
we print the value stored in average (15.0).
Code and execute
luisAge = 10
lauraAge = 20
sum = luisAge + lauraAge
average = sum/2
ee
print(average)
Figure 5-7 shows the output on the screen when
running the above code. As we can see, the result is
15.0, which means that average is of type float. It is
because division in Python always generates a float
type (regardless of the type of the numbers being
divided).
[> 15.0
Figure 5-7. Execution of the previous code.
5.6. The type function