1.3. Variables#
1.3.1. Introduction#
Python stores data in variables. To assign data to a variable we use the = sign.
For example,
x = "Alison"
One way to think of variables is to treat them like a box. In the above example, we have a box named x, and the box is storing the value 10.
When we want to use the value x, we look for the box labelled x and extract the contents.
Here is an example:
x = "Alison"
print(x)
Note that the variable x does not have quotes but the string ‘Alison’ does!
1.3.2. Exercises#
What do you think the output of the following code will be?
name = 'Steve'
print('Hello')
print(name)
Hello
Steve
Hello
name
Hello
Steve
First the program will print the string 'Hello', then the code
will print the information stored in the variable name. This will
result in the program printing:
Hello
Steve
What do you think the output of the following code will be?
x = '3'
print('My lucky number is')
print('x')
My lucky number is
3
My lucky number is
x
My lucky number is
3
Which of the following are valid? Select all that apply.
print(x)
The variable x does not exist so when the program tries
to access it you get an error.
'message' = Happy Birthday
print(message)
Variables should be defined without the quotes and strings
should be defined with quotes. Note that the variable name
must always be to the left of the =.
day = 'Monday'
print('Today is')
print(day)
Well done!
print('I do not like')
print(dislike)
dislike = 'eggs and ham'
The program will run line by line. The variable dislike
isn’t defined until line 3, so when the program tries to
access the variable on line 2, it doesn’t exist yet!
First the program will print the string 'My lucky name is',
then the code will print the string 'x'. This is because there
are quotes around the x so it’s treated as a string.
This will result in the program printing:
My lucky name is
x