Chapter 1 – Introduction to Blockly with Zumis

1.4 – Variables

What are Variables?

Variables are items that are created to be used by a program to store, access and modify data that is used in that program.

Just like humans keep track of values in our brains, computers keep track of values in their program memory using variables. Think of variables as storage containers in your program’s memory. You can create more than 1 variable, and they can hold various different values.

How to create variables in Blockly?

 

To create variables in Blockly, navigate to the Variables page in the block menu bar and click the Create Variable button available on the top left corner of the page.

A pop up will appear allowing you to name your variable. Variables should have descriptive names so you can easily find that information later. For example, if you were creating a variable to store number of seconds, you could call it **seconds**.

You can create as many variables as you like using this same process.

Setting a variable value

 

Once you create a variable, new blocks will appear in the menu. One sets the value of the variable and one gets the value in the variable from your program storage.

To set the value of a variable, drag the “set [variable-name] to” block to the workspace. Next, select any sort of value block and connect it to the “set [variable-name] to” block.

For example, to set the value of a variable to 1, the number block from the math menu can be attached to the “set [variable-name] to” block.

Using variables

 

Once a variable has been created, you can use it in your program. Replace all of the blocks with the variable’s block. From the “Variables” menu, choose the “get” blocks to retrieve the variable from memory. Think about “getting” the variable from storage!

Changing a variable

The value of a variable can simply be changed, by changing the value attached to the “set [variable-name] to” block. This ensures that you are able to change the variable in one spot, and apply this change everywhere.

Activity

 

Try to create a new variable called name and store your name in it. Then, use it in a program to print it to the terminal, using the print block from the “Input/Output” menu.

Conclusion

 

And that’s a wrap on variables!

In this lesson, you learned how to:

– Create and name a variable
– Set a variable to a value
– Use the variable’s value in your program
– Set the variable to a different value in the middle of the program

Get ready to use these variables to create awesome programs ahead!

 

Demo

 

Questions

License

Share This Book