O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Introducing Variables

Variables are a way of storing information in a program so you can refer back to it later or reuse it. You give that piece of information a name, and then you can refer to it by that name in your script. For example, we want to keep a running tally of the score, and we use a variable to do that. They’re called variables because their value can change over time. The score is zero at the start of the game, for example, but it goes up each time the player zaps an alien out of the sky.

We can tell our script to reset the score to zero, increase it when an alien is hit, and display the score at the end. Each time, we just refer to it as score, and the program works out what number that refers to.

To create a variable, click the Variables button above the Blocks Palette. In the Blocks Palette itself is a button called Make a Variable. Click that, and you will be asked for the variable’s name, which is score in this case.

technicalstuff.eps You’re also asked whether this variable should be for all sprites or just for the sprite you’re working on now. It’s important to get this right. For our score, we want to make a variable that all our sprites can see. If you have a variable that’s only used by one sprite, it’s better to create a variable that’s only for that sprite because it stops other sprites from being able to interfere with it. When you duplicate a sprite, all its scripts and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required