Intro to Scratch Programming: If/Else and Variables

Variables can be used to store data. Two main types of variables are numbers and strings. Strings are words or phrases.

This program has a variable called answer that’s created when we use the ask block. The value of answer is whatever name the user enters in response to the question “What’s your name?”

We can use our variable to greet the user by name! Our say block includes a join — this concatenates, or glues together, the phrase “Hello, ” with the value of our answer variable. So if you entered the name “Jane” it would say “Hello, Jane”

See our Scratch variables in action!

The If/Else block can be used to choose between two options based on input.

Just like in our greeting program, we have an ask block that stores its response in the variable called answer.

The value of answer is used to make a choice. If the value is equal to “city”, Scratch changes the backdrop to Colorful City.

The else block contains a nested if statement testing if the value of answer is farm. If it is, Scratch changes the backdrop to Farm.

We need this additional check because the text box allows the user to enter any word and we don’t want everything that isn’t “city” to send them to the farm!

See our If/Else statements in action on Scratch!

Here’s is a more complex program that uses variables, loops, and nested if statements.

The first block has Scratch set the value of the variable my variable  to a random number between 1 and 10.

Next there is a repeat until loop that runs until the value of answer is equal to my variable — that is, until the user has the correct guess.

If answer is equal to my variable, nothing in the loop runs. Scratch runs the next block, which says “You got it!”

This may seem strange as a first step, even before the ask block. In practice, our loop will have to run at least once to have a value for answer that can match my variable. The repeat until condition says when the loop can stop running: when we have the answer.

The first step in every loop is to ask for a number and store that number in answer. We check if answer is too high or too low, to give the user a hint. Then we loop back up to the top to see if maybe the answer is just right.

Sounds like fun? Maybe you’d like to play our number guessing game on the Scratch website.