Week 2 of 8
Variables and Data Types
Students give the program a memory. They store words and numbers in variables, then reuse them to build sentences, so changing one line changes the whole program. This is the first step toward a game that can talk about a player by name and keep track of a score.
- Estimated time
- 50-60 minutes
- Project
- About Me Generator
The idea
A variable is a labeled box: you put a value in it once, then use its name anywhere you want that value. Text goes in quotation marks (a string); numbers do not. With an f-string you can drop a variable straight into a sentence, so a program can greet a player by name instead of saying the same thing every time.
What you will learn
- Make a variable and store a value in it with =.
- Tell the difference between text (a string) and a number.
- Use a variable inside a printed sentence with an f-string.
- Find and fix a variable that was used the wrong way.
New words
- variable
- A named box that stores a value so you can use it again later.
- assign
- To put a value into a variable using the = sign.
- integer
- A whole number with no decimal point, like 10.
- f-string
- A sentence that starts with f, where anything inside { } is filled in from a variable.
Project: About Me Generator
Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.
Run your program to see the output.
Expected output
Player: Alex
Age: 10
Favorite game: soccerMini challenge
Add a variable called score and set it to 0, then print a line like Score: 0. You will track a score exactly like this in your final game.
Debugging challenge
This should print My name is Alex, but it prints the word name instead. The variable's value is not getting filled in. What has to go around name inside an f-string?
Broken code
name = "Alex"
print(f"My name is name.")Show solutionHide solution
Put curly braces around the variable so Python fills in its value:
print(f"My name is {name}.")Extension challenge
Add a number variable called high_score and print one sentence that uses both name and high_score, like: Alex's best score is 25.
Reflect
You changed what the program says just by changing one variable. Why is that better than typing the player's name over and over in every line?
Teacher notes
Reinforce two rules: strings get quotes, numbers do not; and inside an f-string a variable only works with curly braces around it. The classic bug is quoting a variable name so it prints literally, which is worth letting students discover. Keep variable names lowercase and descriptive (score, not x).
Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.
Finished this lesson? Mark it complete to unlock the next week.