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.
Assign and display a variable
- Create a variable and change its name to
- Use a Text block to assign its value to the name that you want.
- Use the print block to display the value of
namein a pop-up.
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
messageand attach it below the name variable block.
- Attach the "create text with" block to your
messagevariable to assign it a value.
- Use this block to combine the text "Hello " with
- Change your print block so it prints