Variables
A variable in Python is a named container that stores a value in your program's memory, letting you label data and reuse or change it as the code runs.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Learn how to store, name, and work with different types of data in Python — the foundation of every program.
A variable is a named container that stores a value in your computer's memory.
Without variables, your program would be stuck . It couldn't:
Let's look at how variables work together in a real scenario. Here's a simple receipt calculator — the kind of logic that powers every online shop:
Every variable has a clear, descriptive name. You can read this like a sentence. That's the goal of good variable naming.
Notice the :.2f inside the f-string — that formats a float to 2 decimal places (like £29.99, not £29.990000). You'll learn more formatting tricks as you progress.
In Python, you create a variable using the = sign:
Every variable stores a type of data. Python has 4 basic types you must know:
Strings are the most common data type in real programs — almost every app deals with text. Here's everything you need to know at this stage.
String methods — built-in actions you can call on any string
Methods are called using a dot . after the variable name. Python has dozens of string methods — these are the most useful ones to start with.
Need to store text that spans multiple lines? Use three quotes:
Triple quotes preserve all line breaks and indentation exactly as written. Very useful for long messages, templates, or documentation.
Escape characters — special characters inside strings
The backslash \ tells Python "this next character is special". The most common are \n (new line) and \t (tab).
len() works on any string. It counts every character — letters, numbers, spaces, and symbols.
Numbers seem simple — but there are a few behaviours that surprise beginners every time.
The regular / operator always returns a float in Python 3, even when dividing 10 by 2. If you need a whole number, use // .
Python lets you add underscores to large numbers to make them easier to read — Python ignores them:
These built-in functions work without any imports — Python provides them automatically.
This isn't a Python bug — it's how computers store decimal numbers in binary memory. It affects every programming language. The fix is simple: use round() when displaying financial or precise values.
Booleans look simple — just True or False — but they're the most powerful type in programming. Every decision your program makes comes down to a boolean.
You'll often get booleans by comparing values. These are called comparison expressions and you'll master them fully in Lesson 3:
Truthy and Falsy — every value has a boolean equivalent
Python can treat any value as True or False. This is called truthiness :
You don't need to memorise all of these now. Just know that the concept exists — it will click naturally when you reach conditional statements.
Python has strict rules for variable names. Break them = error.
Python has community-agreed naming conventions (called PEP 8 style). Following them makes your code immediately readable to every other Python developer on earth.
Use lowercase words separated by underscores for all regular variables and function names:
camelCase (like the second column) is valid Python but is the convention in other languages like JavaScript and Java. Stick to snake_case in Python.
A constant is a variable whose value should never change after it's set. Python doesn't enforce this — it's purely a convention to signal intent to other developers:
When you see ALL_CAPS, it means: "this value is fixed — don't change it elsewhere in the code." Other developers will immediately understand this convention.
One-character variable names (x, y, z) are only acceptable in short mathematical formulas. For everything else, use descriptive names. Your future self will thank you.
Variables can be changed at any time. The old value is replaced.
Python has some elegant shortcuts for assigning and rearranging variables that you'll use constantly.
The number of variables on the left must exactly match the number of values on the right — otherwise Python raises a ValueError .
Swapping two variables — Python's elegant trick
In most languages, swapping two variables requires a temporary "placeholder" variable. Python doesn't:
This works because Python evaluates the entire right side first, then assigns. It's one of the small reasons developers enjoy writing Python.
There are multiple ways to display variables:
Python adds spaces automatically between items.
⚠️ Must convert numbers to string with str()!
Start with f , put variables in {' '} — cleanest option!
Sometimes you need to convert one type to another:
Type conversion looks simple — but there are important edge cases that will catch you out if you're not aware of them.
To convert "3.14" to an integer, you need to go through float first:
Notice: int() truncates (drops the decimal) rather than rounding. int(3.9) gives 3 , not 4 .
Errors are normal! Here's what you'll see most often:
Let's put everything from this lesson together into one real program. Read it line by line — every concept here is something you've learned in Lessons 1 and 2.
You haven't formally learned this yet — that's Lesson 3. But you can probably guess what it does just from reading it. That's Python's readability at work. By the end of Lesson 3 you'll write exactly this kind of logic yourself.
A: A named storage location that holds data your program can use or change later.
A: Strings (text), Integers (whole numbers), Floats (decimals), Booleans (True/False).
A: No — they must start with a letter or underscore.
Q: Why do I get "TypeError: can only concatenate str..."?
A: You're trying to combine text + number. Use str() to convert, or use an f-string.
A: f-strings! They're cleaner and don't require type conversion: f"Age: {' '}"
Lesson 2 complete — you now speak Python's data language!
You can create variables, work with all 4 core data types, update values with shorthand operators, and print output three different ways. Every single Python program ever written uses exactly these skills.
🚀 Up next: Operators & Expressions — learn how to do math, compare values, and combine conditions in Python.
Practice quiz
Which symbol creates (assigns to) a variable in Python?
- ==
- =>
- =
- :=
Answer: =. A single = is the assignment operator. == is for comparison.
What are the 4 basic data types taught in this lesson?
- str, int, float, bool
- str, list, dict, set
- int, long, double, char
- text, number, decimal, flag
Answer: str, int, float, bool. The four core types are str, int, float, and bool.
What does type(3.14) return?
- <class 'int'>
- <class 'float'>
- <class 'str'>
- <class 'decimal'>
Answer: <class 'float'>. A number with a decimal point is a float.
Which is a VALID Python variable name?
- 2name
- user-name
- _count
- my name
Answer: _count. Names may start with a letter or underscore; no hyphens, spaces, or leading digits.
What does print(10 / 2) output?
- 5
- 5.0
- 5.5
- 2
Answer: 5.0. The / operator always returns a float in Python 3, so 10 / 2 is 5.0.
What is the value of int(float('3.9'))?
- 4
- 3.9
- 3
- Error
Answer: 3. int() truncates (drops the decimal) rather than rounding, giving 3.
After a = 5; b = 10; a, b = b, a, what is a?
- 5
- 10
- 15
- None
Answer: 10. Python evaluates the right side first, so the swap makes a = 10.
What does bool('') evaluate to?
- True
- False
- Error
- None
Answer: False. An empty string is falsy, so bool('') is False.
Which is the best (modern) way to print a variable inside text?
- Comma separation
- + concatenation with str()
- f-strings
- % formatting
Answer: f-strings. f-strings like f"{name}" are the cleanest, most modern option.
Using a variable that was never created raises which error?
- TypeError
- SyntaxError
- NameError
- ValueError
Answer: NameError. Referencing an undefined name raises a NameError.