Let’s start with a simple truth: computers are terrible at remembering things.
If you tell one something and don’t store it, it forgets immediately, like a goldfish with a bad Wi-Fi connection.
That’s why Python has variables: Tiny boxes that remember stuff for you.
You give each box a name and fill it with information: a number, a word, maybe even a whole sentence. Whenever you need that information again, you just call the box by its name, and boom, Python hands it back, no questions asked.
Think of variables as labeled containers for your ideas.
You could have one box called age with the number 25 inside, another called name holding "Alex", and maybe one called mood that currently says "tired". Change what’s inside the box, and Python updates its memory instantly.
You’re not just writing code anymore, you’re teaching Python to remember.
And once you’ve mastered that, you’re halfway to teaching it how to think.
SuperPyDuck
Fun Fact
Computers forget faster than you can say print(“Oops!”).
That’s why Python variables exist.
SuperPyDuck
Fun Fact
Computers forget faster than you can say print(“Oops!”).
That’s why Python variables exist.
What’s a Variable, Really?
Let’s keep it simple.
A variable is just a name you give to a piece of information you want Python to remember.
Think of it as a tiny labeled box sitting in Python’s memory. You write the label on the box, then drop something inside.
Example:
age = 25
Here, age is the label, and 25 is what’s inside the box.
So when you later write:
print(age)
Now, here’s the part that trips people up:
The = sign in Python doesn’t mean equals like in math.
It means “store this value inside that box.”
So this line:
age = 25
reads as:
“Hey Python, create a box called
ageand put the number 25 inside.”
If you later write:
age = 26
Python doesn’t get confused, it just replaces what was in the box with the new value.
“Variables don’t argue, they just update.”
You can store all kinds of things inside these boxes:
Numbers (like
5or3.14)Text (like
"Hello"or"blue")Even results from calculations or other boxes
Python’s pretty chill about it — you just have to tell it what you want stored, and it remembers until you change it or close the program.
Your First Variables
Alright, time to open Thonny again! We’re going to make Python remember a few things for the first time.
Start with this simple code:
name = "Alex"
age = 25
favorite_color = "blue"
print(name)
print(age)
print(favorite_color)
When you press Run, you should see:
Alex
25
blue
Each of those lines in the code is like handing Python a new box:
nameholds"Alex"ageholds25favorite_colorholds"blue"
And every time you call print(), Python peeks inside the box and shows you what’s there.
That’s really all a variable does; it stores something you’ll need again later.
And here’s the fun part: it can remember anything; names, numbers, colors, jokes, or even your favorite pizza topping.
Try this:
topping = "pepperoni"
print("My favorite pizza topping is", topping)
Python doesn’t judge. It just remembers what you tell it.
Variable Naming Rules (Without Boring You)
Now that you know what variables are, let’s make sure you name them in a way that keeps Python happy… and future you sane.
Python is flexible, but it’s also a bit picky about names. Here’s how to stay on its good side:
1. Start with a Letter or an Underscore
You can’t start a variable name with a number.
age = 25 # ✅ Works
_name = "Alex" # ✅ Works
name_1 = "Alexander" # ✅ WWorks
1player = "Luna" # ❌ Error! Can’t start with a number
Python likes names that start with letters.
2. Use Only Letters, Numbers, and Underscores
No spaces, no special characters, no emojis (sorry).
favorite_color = "blue" # ✅ Works
favorite color = "blue" # ❌ Nope, spaces cause errors
If you need to separate words, use underscores. It’s like Python’s version of a spacebar in variable names and others.
3. Python Cares About Uppercase and Lowercase
Name, name, and NAME are all different variables.
This can be helpful — or totally confusing if you’re not careful.
Name = "Alex"
name = "Sam"
print(Name)
print(name)
Output:
Alex
Sam
Python sees case differences the same way a grammar teacher does, and it will notice.
4. Don’t Use Python’s Reserved Words
Some words are already special in Python, like print, if, while, and for.
If you try to use them as variable names, Python will roll its eyes and throw an error.
if = "maybe" # ❌ Won’t work
print = "nope" # ❌ Definitely not
It’s like trying to name your pet ‘Dog.’ Technically possible, but really confusing.
5. Make Names That Actually Mean Something
You can name your variable x, but good luck remembering what it was for next week.
x = 25 # 😐 Works, but unclear
age = 25 # ✅ Much better
player_score = 120 # ✅ Even better
Your goal is to make your code self-explanatory, not mysterious.
Good variable names are like good labels on a fridge; they save you from opening everything to find the milk.
Playing with Numbers
Variables aren’t just for words. They’re also great at holding numbers, and Python loves doing math with them.
Let’s start simple:
x = 10
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
When you run this, Python gives you:
13
7
30
3.333333333333333
You just made Python do addition, subtraction, multiplication, and division. All using values stored in variables.
What’s Happening Here
Every time Python sees a line like x + y, it looks inside the boxes for x and y, grabs the numbers, does the math, and (optionally) shows you the result with print().
You tell Python what’s in the boxes, and it handles the calculator part.
Saving the Result in a New Variable
You can even store the result of the math in another box:
x = 10
y = 3
result = x + y
print(result)
Output:
13
Now you have a new box (result) that holds the outcome of your calculation.
If you later change x or y, the math changes too, Python always uses the most recent values.
More Operations to Try
Here are a few more symbols you’ll see often:
| Symbol | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 9 - 4 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division (always gives a float) | 10 / 4 | 2.5 |
// | Floor division (drops decimals) | 10 // 4 | 2 |
% | Modulo (gives remainder) | 5 % 2 | 1 |
** | Exponent (power of) | 2 ** 3 | 8 |
Example: A Simple Shopping Math
Let’s make it a bit more real.
apple_price = 3
bananas = 4
total = apple_price * bananas
print("The total cost is:", total, "USD")
Output:
The total cost is: 12 USD
You just made Python your personal cashier.
Changing What’s in the Box
One of the coolest things about variables is that they’re not carved in stone. They’re more like sticky notes you can rewrite whenever you like.
Let’s try it:
mood = "happy"
print(mood)
mood = "tired"
print(mood)
Output:
Output:
happy
tired
You didn’t need to create a new variable, you just changed what was inside the old one.
Python simply erases the old value ("happy") and replaces it with the new one ("tired").
It’s that easy.
Variables don’t cling to the past; they move on instantly when changed.
Another Example
Let’s imagine you’re keeping track of a player’s score in a game:
score = 0
print("Starting score:", score)
score = score + 10
print("Updated score:", score)
Output:
Starting score: 0
Updated score: 10
You’re telling Python:
“Take what’s in the
scorebox, add 10, and store the new total back in the same box.”
This pattern — x = x + something — is incredibly common in programming.
It’s how you update running totals, counters, points, or progress bars.
Shortcut Version
Python has a neat shortcut for that kind of update:
score += 10
That line means exactly the same thing as score = score + 10, but it’s shorter and cleaner.
You can also use:
score -= 5 # subtract 5
score *= 2 # multiply by 2
score /= 3 # divide by 3
Python loves shortcuts. It’s lazy in the efficient way.
Combining Variables
So far, you’ve made Python store and update bits of information. Now it’s time to make those pieces work together.
You can combine variables to form sentences, show results, or tell little stories.
Let’s start simple.
Combining Text Variables
name = "Alex"
hobby = "painting"
print("My name is " + name + " and I love " + hobby + ".")
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
My name is Alex and I love painting.
Here’s what’s happening:
Python glues together the text and variables using
+.Each piece you add becomes part of one big string (a fancy word for text).
“The
+sign doesn’t always add. Sometimes, it just plays matchmaker for words.”
Numbers Are Different
If you try to mix numbers and text directly, Python gets a bit cranky:
age = 25
print("I am " + age + " years old.")
This causes an error, because Python can’t add numbers and text with +.
But you can fix it by turning the number into text using str():
age = 25
print("I am " + str(age) + " years old.")
Output:
I am 25 years old.
The Easier Way: f-Strings
Python has a modern, super clean way to mix text and variables: f-strings.
name = "Alex"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alex and I am 25 years old.
Everything inside {} is replaced by the value of the variable.
You don’t need to convert numbers, and it looks much cleaner.
“f-strings are like fill-in-the-blank sentences for coders.”
Try It Yourself
Write a few of your own lines. Like a self-introduction or a mini bio.
name = "Luna"
city = "Miami"
pet = "cat"
print(f"Hi, I’m {name}, I live in {city}, and my pet is a {pet}.")
Once you run it, change a few variables and watch the output update automatically, no need to rewrite your print line.
That’s the beauty of variables: change the data, not the program.
Checking What’s Inside
Sometimes you’ll forget what kind of data a variable holds. Is it text, a number, a decimal, or something else entirely?
Luckily, Python has a built-in detective for that: type().
Meet type()
type() tells you what’s inside a variable’s box. Not the value itself, but the type of value.
Try this:
name = "Alex"
age = 25
height = 1.8
print(type(name))
print(type(age))
print(type(height))
Output:
Here’s what those weird labels mean:
| Type | What It Means | Example |
|---|---|---|
str | String – text in quotes | "Alex", "blue", "Hello!" |
int | Integer – whole number | 25, 100, -3 |
float | Floating point – number with decimals | 1.8, 3.14, 0.5 |
Why It Matters
Sometimes Python needs to know what kind of thing it’s dealing with.
You can’t do math with "banana", and you can’t capitalize the number 42.
Knowing a variable’s type helps you decide what you can do with it or what needs to be converted first.
For example:
age = "25"
print(age + 5) # ❌ This gives an error
That fails because "25" is stored as text (a str), not a number.
But if you store it as an integer:
age = 25
print(age + 5)
Output:
30
Now Python knows it’s dealing with numbers and does the math happily.
“Strings talk. Integers count. Floats… float.”
Python doesn’t mix data types. It’s like a picky eater who refuses to blend spaghetti and ice cream.
Common Mistakes (And How to Laugh Them Off)
Even the best programmers mess up their variables, and beginners? We do it a lot.
The good news? Every mistake teaches you exactly how Python thinks.
Let’s go through the most common ones so you can spot them, fix them, and move on like a pro.
1. Forgetting the Quotes
name = Alex
print(name)
Python will immediately shout something like:
NameError: name 'Alex' is not defined
That’s because without the quotes, Python thinks Alex is another variable, not text.
Always wrap text in quotes ("Alex" or 'Alex').
Correct version:
name = "Alex"
print(name)
2. Misspelling Variable Names
name = "Alex"
print(naem)
Output:
NameError: name 'naem' is not defined
Python doesn’t guess what you meant.
If you mistype even one letter, it thinks you’re talking about a whole new (nonexistent) variable.
Tip: Stick to short, clear names that are hard to misspell, or copy-paste when possible.
3. Using Spaces in Variable Names
first name = "Alex"
print(first name)
Python immediately breaks down:
SyntaxError: invalid syntax
You can’t have spaces in variable names. Use underscores instead:
first_name = "Alex"
print(first_name)
Python hates spaces in names because it can’t tell if you’re naming something or starting a new command.
4. Mixing Text and Numbers Without Conversion
age = 25
print("I am " + age + " years old.")
Output:
TypeError: can only concatenate str (not "int") to str
Python refuses to mix text ("I am ") and numbers (25) with a +.
You have to tell it to convert the number first:
print("I am " + str(age) + " years old.")
Or even better:
print(f"I am {age} years old.")
5. Forgetting to Assign a Value
color
print(color)
Output:
NameError: name 'color' is not defined
If you never gave the variable a value, Python doesn’t know what to do with it.
Always make sure your boxes actually have something inside.
color = "green"
print(color)
These mistakes are part of the process, not signs you’re failing.
Every red error message is Python saying, “Hey, let’s talk about this.”
Learn to read them, fix them, and move on. That’s what every programmer, beginner or NASA engineer, does every single day.
Mini Challenge: Meet the Data Keeper
Alright, PyHero! It’s time to test your new powers.
You’ve learned to make Python remember things, change them, and even talk about them.
Now, let’s build a tiny program that uses everything you’ve just learned. Nothing too serious, just something to prove you’re in control.
Your Mission
Create a new file in Thonny called my_info.py.
Inside it, you’ll make Python act like your personal data keeper; storing a few facts about you and showing them back in a complete sentence.
Step 1: Store Some Facts
Pick a few things about yourself and turn them into variables:
name = "Luna"
age = 27
favorite_food = "pasta"
Step 2: Make Python Talk
Now, use an f-string to let Python introduce you:
print(f"Hi, I’m {name}, I’m {age} years old, and my favorite food is {favorite_food}.")
Output:
Hi, I’m Luna, I’m 27 years old, and my favorite food is pasta.
Boom! You’ve just made Python hold onto your data and use it in a sentence.
Step 3: Update the Info
Change one of your variables and run the program again.
name = "Luna"
age = 27
favorite_food = "sushi"
print(f"Hi, I’m {name}, I’m {age} years old, and my favorite food is {favorite_food}.")
Output:
Hi, I’m Luna, I’m 27 years old, and my favorite food is sushi.
No need to change the print line. Python automatically updates the text because the variable changed.
Bonus Challenge
Add one more variable of your choice. Maybe your favorite color, a hobby, or your dream destination, and include it in your sentence.
Get creative!
Let's wrap up!
Take a second to appreciate this moment, you’ve officially taught Python how to remember things.
That might not sound world-changing yet, but it’s a huge step.
You’ve just learned how to make data stick, how to change it, and how to use it in real sentences. That’s the foundation of almost every program that exists; from small calculators to full-blown video games.
You now know how to:
- Create and name variables
- Store and print data
- Combine text and numbers
- Update what’s stored
- Avoid (and fix) the most common beginner mistakes
“Every game score, every saved password, every online shopping cart — all powered by variables just like the ones you made today.”
You’ve officially leveled up from just typing commands to making your computer think with memory.