Variables - Containers for Data (continued)

📊 Workshop Slides

Purpose of Variables

As reminder: You can think of variables as a label. They are always on the left side of the equal sign (=). Take a look at the code below:

basic.show_string(Who is she?”)
basic.show_string(Supercalifragilisticexpialidocious)
basic.show_string(Whats her name?”)
basic.show_string(Supercalifragilisticexpialidocious) 
basic.show_string(Say that again?”)
basic.show_string(Supercalifragilisticexpialidocious)

Having to type out “Supercalifragilisticexpialidocious” every single time you want to use it would be annoying, wouldn’t it? Instead, we can assign the string “Supercalifragilisticexpialidocious” to a variable called name and use that instead. Then it would look something like this:

name = Supercalifragilisticexpialidocious
basic.show_string(Who is she?”)
basic.show_string(name)
basic.show_string(Whats her name?”)
basic.show_string(name) 
basic.show_string(Say that again?”)
basic.show_string(name)  

That looks a lot cleaner, doesn’t it? We can also do the same with numbers!

basic.show_number(25)

is the same thing as

age = 25
basic.show_number(age)

Define variables before you use them!

If you ask your computer to spell your name, it must know what it is:

image

It also must be defined BEFORE you use them:

image

Sample Exercises

What should go in the question marks?

name = Jacqui
age = 25
basic.show_string(My name is: )
basic.show_string(??) 
basic.show_string(My age is: ) 
basic.show_number(??)
Answer

1) name 2) age

Variables can be changed

name = Jacqui
name = Drshika
basic.show_string(name)

Any guesses as to what will show?

Answer

Drshika

name = Jacqui
basic.show_string(name)
name = Drshika

What about this?

Answer

Jacqui

Variables can do Math

number_one = 1
number_two = 2
basic.show_number(number_one + number_two)

Any guesses to what will show?

Answer

3

number_one = 10
number_two = 2
basic.show_number(number_one - number_two)
Answer

8

number_one = 5
number_two = 5
basic.show_number(number_one * number_two)
Answer

25

number_one = 15
number_two = 5
basic.show_number(number_one / number_two)
Answer

3