Variables and Text
A variable in programming is like a container which holds a value:
You can store a value in a variable for later retrieval:
You've already seen the color variable, which sets the color of a pen. You can create your own variables for storing numbers, text or anything else. These values can be retrieved later in your program for any purpose. Try these small tasks in the blockly editor to get practice using variables.
Text Variables
Assign and display a variable
- Create a variable and change its name to
name
. - Use a Text block to assign its value to the name that you want.
- Use the print block to display the value of
name
in a pop-up.
User input
Instead of setting the value of name
in your code, let's ask the user for their name. Replace the 'hard-coded' text block with a prompt
block that gets input from the user. You can optionally add a message to display in the prompt, such as "Your name please?".
Your print block will now display the user's name in the pop-up.
Creating new variables
Instead of just showing the user their name, can you greet them with a custom message?
- Create a new variable called
message
and attach it below the name variable block. - Attach the "create text with" block to your
message
variable to assign it a value. - Use this block to combine the text "Hello " with
name
. - Change your print block so it prints
message
instead ofname
.
Comments
Stewart
Oct 6, 10:40 AMNone of the Blockly levels seem to count towards or save progress, and on this node there's no way to run the code you create!
Learneroo
Oct 6, 7:30 PMThanks for reporting that issue, the run button had been covered up, but it's now fixed. Sorry that no check mark appears on the side, this is just meant as a short stand-alone intro to programming with blockly.
Stewart
Oct 11, 10:58 AMThank you for the quick fix... the next node has the same issue btw. I've used Blockly with students in the past and love the way you present these tutorials, I'm just looking forward to the check marks appearing so that I can track my students progress through the levels.
Learneroo
Oct 11, 2:15 PMThanks for the feedback, fixed. I'll look into some way students can share the progress.