Skip to content
Binogi logo

Subjects

Variables: Introduction

Variables: Introduction

Video thumbnail
Play

In the sentence "Hello Mikael, how are you?" do we need to use a variable for ...

Variables: Introduction

Look what I’ve done! I’ve programmed the robot to greet me! Hello Lina. - Can the robot greet me too? - Hello Lina What?! I want the robot to say “Hello Maria”. We just reprogram the robot to say “Hello Maria”.

Hello Maria. Fun! But what if someone comes who’s not named Lina or Maria? - Then we’ll just… - Oh no! There must be a better way. What does your pseudocode look like?

The robot says “hello”, and then the name that is stated in the code. But everyone doesn’t have the same name. There is a large variety of names. When something varies like this, it's smart to use a variable. First, we’ll ask the user to enter their name.

Add two lines to the pseudo code, telling the user to do that. Ask the robot to note the name. What actually happens when we give the instruction "Note name"? Let’s look into the robot's brain. Look, there’s a drawer with the label "name".

Let’s have a look what's in it. Here we find the name “Maria”. This drawer is a variable and when we put the name “Maria” in it we assign it a value. To know which drawer we put the name "Maria" in, we have placed a label on the drawer. Once we have labelled the drawer, we have declared the variable.

Now we have control of the drawer, because it has a name that no other drawer has. What's good about that is we can then use the variable name either to look what's in the drawer or to add something, or to replace what's in the drawer. Here’s the pseudocode again. Here the name is saved in the variable labelled "name", and then we use this variable to greet the user with the correct name. There are some rules for what label a variable can have.

We can use lower case letters, like here, but upper case letters work too, capitals. Numbers can be used, as long as the variable name does not start with a digit. We can not have spaces in a variable name. However, we can use the underscore character. Programming languages are almost always in English, so you may want to have the variable names in English as well.

Some special words are reserved as commands in a programming language. Those words can not be used for naming variables. Let’s see how it’s going with the programming. Let’s test our new code. Come here, Leon!

See what we’ve done! Please state your name. Leon. Why? Hello, Leon why.