Variables

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.

../../_images/variable_in.png

When we want to use the value x, we look for the box labelled x and extract the contents.

../../_images/variable_out.png

Here is an example:

x = "Alison"
print(x)

Note that the variable x does not have quotes but the string ‘Alison’ does!

Question 1

What do you think the output of the following code will be?

name = 'Steve'
print('Hello')
print(name)
  1. Hello
    
  2. Steve
    
  3. Hello
    name
    
  4. Hello
    Steve
    
Solution

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
Question 2

What do you think the output of the following code will be?

x = '3'
print('My lucky number is')
print('x')
  1. My lucky number is
    3
    
  2. My lucky number is
    x
    
  3. My lucky number is
    
  4. 3
    
Solution

Solution is locked

Question 3

Which of the following are valid? Select all that apply.

  1. print(x)
    
  2. 'message' = Happy Birthday
    print(message)
    
  3. day = 'Monday'
    print('Today is')
    print(day)
    
  4. print('I do not like')
    print(dislike)
    dislike = 'eggs and ham'
    
Solution

Solution is locked