Using variables
As we have already illustrated, we can create a named item, which here we call ‘x’ for
simplicity, and assign it to a value:
>>> x = 17
Using the above example we can introduce some more jargon computing terms. On the
left-hand side, before the equals sign, we have a variable. On the right-hand side we have
a literal. The whole line here is a statement and specifies that the variable is set to have
value equal to the literal. As you might expect from the term ‘variable’, the value of x may
be changed by assigning a new value:
>>> print(x)
17
>>> x = 3
>>> print(x)
3
In Python the names we give variable data can contain only the usual 26 letters (upper
and lower case), numbers and underscores (‘_‘), with the additional restriction that they
cannot begin with a number. Note that names are case-sensitive, so the variables DNA,
Dna and dna are all treated as distinct. In general, variables should have names that
indicate what their purpose and/or type are, in order to make the code more
understandable. For example, if you state freeEnergy = heat-entropy and not x = p-q, you
can see at a glance what is intended and have your program more easily understood,
including by yourself at a later date, without any additional comments.
We can use as many different variable names as we like and assign their value based on
other variables. For example, in the following we assign a value to x and then assign a
value for y based on x:
>>> x = 17
>>> y = x * 13
>>> print(y)
221
Unlike many computing languages, Python is not a language where you must initially
specify, and then stick to, a given kind or type of data for a given variable. You could
initially allocate a numeric value to ‘x’, without advance warning, and then later on
change ‘x’ to some text. This differs from languages like C and Java, for example, where
you would have to declare up front what type of data ‘x’ was to contain. In Python, the
type of variable is specified by the type of whatever its value is set to. So if you redefine a
variable its type may change. Although variables can change type, it is usually best to
avoid that practice.
>>> x = 4 # x is set to the integer 4
>>> 3*x
12
>>> x = 7.1 # x now set to the floating point number 7.1
>>> 3*x
21.299999999999997
The above example reminds us that floating point calculations are not always precise.
The answer could also depend on the Python implementation and version.
Do'stlaringiz bilan baham: |