Python Variables for Beginners
Learn Python variables through games: store scores, lives and player names, change them with +=, and avoid the most common beginner mistakes.
A variable is a name for a value your game needs to remember: the score, the lives left, the player's name, whose turn it is. You create one with = and can change it whenever you like.
Types of values
- int: whole numbers like
3or-20(scores, lives). - float: numbers with a point like
2.5(speeds, times). - str: text in quotes like
"Sam"(names, messages). - bool:
TrueorFalse(is the game over?).
Swapping turns
Two-player games flip a variable every turn. A conditional expression does it in one line:
Good names
Use lowercase words joined by underscores: high_score, shots_left. Names can't start with a number or contain spaces, and Python cares about capitals: Score and score are different variables.
💡 A NameError usually means a typo, or using a variable before the line that creates it has run.
Games that use Variables
Practise this with 7 of the 20 games:
- #05☆☆☆
Number Guessing Game in Python
Learn The random module, while loops and if, elif and else.
- #06☆☆☆
Pong-Style Paddle Game in Python
Learn Turtle graphics, Functions and if, elif and else.
- #07☆☆☆
Mad Libs-Style Story Game in Python
Learn input() and print(), Strings and Variables.
- #14☆☆☆
Higher or Lower Game in Python
Learn The random module, while loops and if, elif and else.
- #16☆☆☆
Coin Flip in Python
Learn The random module, for loops and Variables.
- #19☆☆☆
Math Quiz Game in Python
Learn The random module, Dictionaries and for loops.
- #20☆☆☆
Typing Speed Game in Python
Learn Strings, Functions and for loops.
Frequently asked questions
What is a variable in Python?
A name that points to a value. score = 0 creates the name score and stores 0 in it. Assigning again replaces the value.
What does += mean in Python?
score += 5 is short for score = score + 5. There's also -=, *= and /=.