Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Arithmetic in Your Programs.”


Reassigning Values to a Variable


After you assign a value to a variable, the variable is not stuck with that value. It can be reassigned.
Variables are called variables because their values can be varied. (Say that three times fast.)


In Listing 4.21, the variable coffee_cup has its value changed from coffee to tea. To reassign
a value, you simply enter the assignment syntax with a new value at the end of it.


LISTING 4.21 Reassigning a Variable


Click here to view code image


>>> coffee_cup = 'coffee'
>>> print ("My cup is full of", coffee_cup)
My cup is full of coffee
>>> coffee_cup = 'tea'
>>> print ("My cup is full of", coffee_cup)
My cup is full of tea
>>>

Did You Know: Variable Name Case
Python script writers tend to use all lowercase letters in the names of variable whose
values might change, such as coffee_cup. For variable names that are never
reassigned values, all uppercase letters are used (for example, PI = 3.14159).
The unchanging variables are called symbolic constants.

Learning About Python Data Types


When a variable is created by an assignment such as variable = value, Python determines and
assigns a data type to the variable. A data type defines how the variable is stored and the rules
governing how the data can be manipulated. Python uses the value assigned to the variable to
determine its type.


So far, this hour has focused on strings of characters. When the Python statement coffee_cup =
'tea' was entered, Python saw the characters in quotation marks and determined the variable
coffee_cup to be a string literal data type, or str. Table 4.2 lists a few of the basic data types
Python assigns to variables.


TABLE 4.2 Python Basic Data Types

You can determine what data type Python has assigned to a variable by using the type function. In

Free download pdf