VARIABLES

Variables are named locations which are used to store references to the object stored in memory. Instead of using the address where the computer stores the value, we assign a name to it. Much like if you were going to the Parliament Building in Ottawa, you probably wouldn’t tell people that you were going to 111 Wellington Street. You would simply say “The Parliament Building”.

In computing, it’s the same thing. We can refer to blocks of memory by a variable name. For instance, let’s take the following code as an example.

x = 42
y = 42

The computer will store the two pieces of data (in this case 42 and 42) in memory. You can access them by using the variables names (in this case x and y).

You can now change the value of one of them very easily. For instance, let’s change the value of y to 78.

You can also have two variables reference the same object. For instance, have a look at the code below.

x = 42
y = x #y has now been assigned the value of x

Be very careful though as the order of your code is important. For instance:

x = 42
y = x

 

will work just fine. But change up the order and you will have problems.

Error 1 – Assigning a Value too Early

y = x  #x does not exist yet nor does it have a value
x = 78 #this will NOT update the previous line

Error 2 – Getting the Wrong Order

x = 42
x = y #This will assign the value of y to x. Since y does not exist yet, you will get an error

Error 3 – Putting the Value Before the Variable

42 = x #You can't assign the value of x to 42. Does not make sense.

 

You Try

Create a variable, assign a value to it, and print the value to the screen. You can copy the code below or create your own.

#printing contents of a variable
a = 25
print(a)

 

Variable Addresses

Earlier we mentioned that you can refer to the Parliament Buildings in Ottawa by simply saying the Parliament Building instead of 111 Wellington Street. Variables have the same process. Notice that we were able to get the contents of the variable by simply typing:

print(a)

But where is the variable stored? You can actually get the address of the variable by referring to its ID. In the example below, we will print the address of the variable a.

#Printing the contents and address of a variable.
#We will convert the address to a hex value before printing

a = 25
print ("The value of a is:",a)
print ("The address of a is:",hex(id(a))) #this line of code is explained below

"""
id(a) is the id value of the variable a
hex() will convert the value to a hexadecimal number
hex(id(a)) will create a hexadecimal number for the id of the variable a. To print it, we must put it in a print() statement.
print(hex(id(a))) will print the value mentioned above.
"""
 

You Try

Create a variable, assign a value to it, and print the value and id (converted to hex) to the screen. You can copy the code below or create your own.

#Create the variable and assign it a value
myVar = 77

#Print the value to the screen
print ("The value of myVar is:",myVar)

#Print the hexadecimal id of myVar to the screen
print("The id of myVar is:", hex(id(myVar)))

 

Identifiers

The names we choose for variables and functions are commonly known as Identifiers. In python Identifiers must obey the following rules.

  1. All identifiers must start with letter or underscore ( _ ) , you can’t use digits. For e.g my_var is valid identifier while 1digit is not.
  2. Identifiers can contain letters, digits and underscores ( _ ). They may not contain a special character (eg. $,%,&)
  3. They can be of any length.
  4. Uppercase and lowercase characters are distinct. This means the variable name ItemsOrdered is not the same as itemsordered.
  5. Identifier can’t be a keyword (keywords are reserved words that Python uses for special purpose). You can see a list of Python Keywords below (next section).

Another general rule (but one that can be broken) is that identifiers should either be be written in CapWords or use underscores to combine words. See below for an example.

Suppose you want to create a variable for the current year. The following code snippet is a bit difficult to read.

currentyear = 2020

It’s the same when someone uses a ridiculously long hashtag in their social media post

#ilovecomputerscienceandidontcarewhoknowsit

It’s much better if you break the words up. This is where you would use CapWords (each word is capitalized) or use underscores in between each word.

Our example above would look much better as:

currentYear = 2020  #CamelCase
current_year = 2020

Much like our hashtag would look much better as:

#ILoveComputerScienceAndIDontCareWhoKnowsIt

or

#I_Love_Computer_Science_And_I_Dont_Care_Who_Knows_It

The final unwritten rule is to use meaningful variable names. While the following code is valid.

p = 130768

it is much easier for the programmer to understand a meaningful variable name such as:

population = 130768

 

 

Keywords

Python reserves certain words in order to perform certain tasks. These words are known as keywords or reserved words and their tasks will become known as we delve deeper into the Python language. For now, just know that the following list of words cannot be used as constants, variables or any other identifier names.

and exec not as False
or assert finally pass break
for print class from raise
continue global return def if
True del import try elif
in while else is with
except lamda yield raise nonlocal

At this point in the course, you’re not supposed to know what that list of words can do. It’s not important.
What’s important is knowing that they can’t be used as a variable’s name.Let’s assume you’re writing a poker video game. In poker, a player can ‘raise’ when they bet. It would then stand to reason that your game would probably have a variable called raise.
This is when Python gets confused.As far as Python knows, the keyword raise has a specific function, and you would end up with an error in your code.

Maybe your raise variable could be called raise_bet or raiseBet? Python would be happier with that!

You Try

Try creating a Python program using the code below. Did you get any errors? If so, fix them so that the program will work and print each of the variables to the screen.

break = 120
1month = 10
my var = 55

 

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material.

1. What is a variable?
2. Which of the following are illegal variable names in Python, and why?
–> x
–> 99bottles
–> july2009
–> theSalesFigureForFiscalYear
–> r&d
–> grade_report

3. Is the variable name Sales the same as sales? Why or why not?
4. Is the following assignment statement valid or invalid? If it is invalid, why?

72 = amount

5. What will be displayed by the following program?

my_value = 99
my_value = 0
print(my_value)

6. Create the following Python programs:
–> A program that will store the string ‘Hello’ in a variable called message. Have the program print the contents of the variable message to the screen.

–>  A program will store the the values listed below to separate variables and then print their contents and type to the screen
Values: 4, 8.98, -0.44, 76.0, -22 (Each should be stored in a different variable)
“Hello. It’s Me”, “%$#” (NOTE: Do not include the quotation marks)

–> A program that will assign a string value to the variables firstName and lastName. It should then print out the following using a single print statement.
Output: Hello, firstName lastname! How are you today? NOTE: firstName and lastName should be replaced with your assigned values when printed.

When you feel you have completed all of the above problems, check your programs versus the sample solutions.