Assignment Statements
The last thing we discussed in the previous unit were variables. We use variables to store values of an evaluated expression. To store this value, we use an assignment statement. A simple assignment statement consists of a variable name, an equal sign (assignment operator) and the value to be stored.
>>> a = 7 # -> Assignment statement
a
in the above expression is assigned the value 7.
>>> a = a + 2
>>> a
9
Here we see that the variable a
has 2 added to it's previous value. The resulting number is 9, the addition of 7 and 2.
To break it down into easy steps:
a = 7
-> Variable is initialized when we store a value in ita = a + 2
-> Variable is assigned a new value and forgets the old value
This is called overwriting the variable. a
's value was overwritten in the process. The expression on the right of the =
operator is evaluated down to a single value before it is assigned to the variable on the left. During the evaluation stage, a
still carries the number 7
, this is added by 2
which results in 9
. 9
is then assigned to the variable a
and overwrites the previous value.
Another example:
>>> myString = 'world'
>>> myString
'world'
>>> myString = 'hello ' + myString
>>> myString
'hello world'
Hence, when a new value is assigned to a variable, the old one is forgotten.
Variable Names
There are three rules for variable names:
- It can be only one word, no spaces are allowed.
- It can use only letters, numbers, and the underscore (_) character.
- It can’t begin with a number.
Examples:
Valid variable names | Invalid variable names |
---|---|
balance | savings-balance (hyphens are not allowed) |
savingsBalance | savings balance (spaces are not allowed) |
savings_balance | 2balance (can't begin with a number) |
_hello | 35 (can't begin with a number) |
HELLO | hell$$0 (special characters like $ are not allowed) |
hello5 | 'hello' (special characters like ' are not allowed) |
Note: Variable names are case-sensitive. This means that hello, Hello, hellO are three different variables. The python convention is to start a variable name with lowercase characters.
Tip: A good variable name describes the data it contains. Imagine you have a cat namely Kitty. You could say
cat = 'Kitty'
.
Questions:
What would this output:
'name' + 'namename'
? a.'name'
b.'namenamename'
c.'namename'
d.namenamename
What would this output:
'name' * 3
a.'name'
b.'namenamename'
c.'namename'
d.namenamename