Variables and Basic Data Types
In the last lesson, we made Python output a "Hello, World!" line. But if all we could do was output fixed text, programming would be boring. This lesson introduces variables — the most fundamental concept in programming. Think of them as labeled boxes for data, letting you store and modify values anytime.
1. What Is a Variable
A variable is a name for a piece of data. Imagine it as a labeled box: the label has a name (variable name), and the box holds the data (value).
# Define a variable named age, storing the number 18
age = 18
When you write age = 18, Python does two things:
- Allocates memory space and stores the number
18. - Attaches the label
ageto that space.
From then on, age represents the number 18 — you can use it in calculations, output, or modify it:
print(age) # Output 18
print(age + 5) # Output 23
age = 20 # Change the value — the content of the box changes
print(age) # Output 20
age = 18, later you change it to age = 20. The same name can point to different values — this is crucial in programming.
2. Variable Naming Rules
Python has strict rules and community conventions for variable names:
Must Follow (or get an error)
| Rule | Correct Examples | Wrong Examples |
|---|---|---|
| Only letters, digits, underscores | my_name, age2 |
my-name (hyphen not allowed) |
| Cannot start with a digit | name1 |
1name |
| Cannot be a Python keyword | my_if |
if (if is a keyword) |
| Case-sensitive | name and Name are different |
— |
Python has 35 keywords (also called reserved words), such as if, for, while, import, class, def, return. These are part of Python's syntax and cannot be used as variable names.
Recommended Conventions (PEP 8)
PEP 8 is Python's official style guide, widely followed in the industry:
- Use lowercase with underscores for variable names (snake_case):
student_name,total_score, notstudentName(camelCase). - Use ALL CAPS for constants:
PI = 3.14159,MAX_SIZE = 100(Python has no true constants; uppercase is a convention meaning "please don't modify me"). - Use meaningful names:
ageis better thana,total_studentsis better thants. Code is meant to be read — good names save half the comments.
# Good names (clear at a glance)
total_price = 99.9
student_count = 35
# Bad names (unclear purpose)
a = 99.9
b = 35
3. Basic Data Types
Python has 5 commonly used basic data types:
| Type Name | Python Name | Example | Description |
|---|---|---|---|
| Integer | int |
42, -1, 1000 |
Whole numbers without decimals |
| Float | float |
3.14, -0.5, 2.0 |
Numbers with decimals |
| String | str |
"Hello", 'Python' |
Text, enclosed in quotes |
| Boolean | bool |
True, False |
Represents true/false, capitalized |
| None | NoneType |
None |
Represents "nothing," capitalized |
# Define a variable for each type
age = 25 # int
price = 19.99 # float
name = "Xiao Ming" # str
is_student = True # bool
result = None # NoneType
print(age) # Output 25
print(price) # Output 19.99
print(name) # Output Xiao Ming
print(is_student) # Output True
print(result) # Output None
Checking Type with type()
If you're unsure about a variable's type, use type():
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
Dynamic Typing
Python is dynamically typed — the same variable can hold different types at different times:
x = 10 # x is an integer
print(x) # Output 10
x = "Hello" # Same variable, now a string
print(x) # Output Hello
x = True # Now a boolean
print(x) # Output True
This is not allowed in statically typed languages like C++ or Java — once declared, the type is fixed. Dynamic typing offers flexibility and concise code, but a variable accidentally changing type can cause runtime errors (we'll see examples later).
4. More print() Features
We saw print() in Lesson 01. Here are two more useful tricks:
Outputting Multiple Values with Commas
name = "Xiao Hong"
age = 22
print("My name is", name, "and I'm", age, "years old")
# Output: My name is Xiao Hong and I'm 22 years old
print() automatically adds a space between arguments. To change this, use the sep parameter:
print("2026", "06", "19", sep="-")
# Output: 2026-06-19
Using end to Control Line Endings
By default, print() adds a newline after output. Use end to change this:
print("First line", end=" → ")
print("Second line", end=" → ")
print("Third line")
# Output: First line → Second line → Third line
5. f-strings: Embedding Variables in Strings
You've already seen f"Hello, {name}" in earlier examples. This is called an f-string (formatted string), the most common way to format strings in Python. Simply put: prefix the string with f, wrap variables in {}, and Python replaces them with their values.
name = "Xiao Hong"
age = 22
print(f"My name is {name}, I'm {age} years old.")
# Output: My name is Xiao Hong, I'm 22 years old.
You can put not just variable names, but expressions inside the curly braces:
a = 10
b = 3
print(f"{a} + {b} = {a + b}") # Output: 10 + 3 = 13
print(f"{a} × {b} = {a * b}") # Output: 10 × 3 = 30
You can also control number formatting:
pi = 3.14159265
print(f"π = {pi}") # Output: π = 3.14159265
print(f"π ≈ {pi:.2f}") # Output: π ≈ 3.14 (2 decimal places)
print(f"π ≈ {pi:.4f}") # Output: π ≈ 3.1416 (4 decimal places)
# Add thousands separator
big = 1234567
print(f"{big:,}") # Output: 1,234,567
:.2f, the colon starts the format spec — . means decimal, 2 is the number of digits, f means float. :, adds a thousands separator. Don't worry about memorizing — you'll pick it up with practice.
6. Examples
Example 1: Store Personal Info with Variables (Difficulty ⭐)
This shows how to store personal information and reference it in output.
# Store personal info in variables
name = "Zhang San" # String — text enclosed in quotes
age = 28 # Integer — whole number
height = 1.75 # Float — number with decimal
is_programmer = True # Boolean — either True or False
# Use f-strings to embed variable values in output
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height} m")
print(f"Learning programming: {is_programmer}")
# Fun fact — ratio of height to age
print(f"{name}'s height is {height / age:.3f} times their age")
Output:
Name: Zhang San
Age: 28
Height: 1.75 m
Learning programming: True
Zhang San's height is 0.062 times their age
The :.3f in {height / age:.3f} means "keep 3 decimal places."
Example 2: Operations Between Variables (Difficulty ⭐⭐)
Different types support different operations. Be aware of the rules.
# Numeric operations
a = 10
b = 3
print(f"{a} + {b} = {a + b}") # Addition: 13
print(f"{a} - {b} = {a - b}") # Subtraction: 7
print(f"{a} * {b} = {a * b}") # Multiplication: 30
print(f"{a} / {b} = {a / b}") # Division: 3.333... (float result)
print(f"{a} // {b} = {a // b}") # Floor division: 3 (integer part only)
print(f"{a} % {b} = {a % b}") # Modulo: 1 (remainder)
print(f"{a} {b} = {a b}") # Power: 10³ = 1000
# String concatenation
first_name = "Zhang"
last_name = "San"
full_name = first_name + last_name # + concatenates strings
print(f"Full name: {full_name}")
# Different types can't be mixed
# This would error: can't add a string and a number
# result = "Age: " + 25 ← uncomment to try
Output:
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000
Full name: Zhang San
+ between numbers is addition; between strings is concatenation. But you can't use + between a string and a number. If needed, convert manually: "Age: " + str(25). The str() function converts other types to strings.
Example 3: Multiple Assignment and Swapping (Difficulty ⭐⭐⭐)
Python has concise syntax for elegant code:
# Assign multiple variables in one line
x, y, z = 10, 20, 30
print(f"x={x}, y={y}, z={z}") # x=10, y=20, z=30
# Swap two variables — other languages need a temp variable
# Python does it in one line
a, b = 5, 10
print(f"Before swap: a={a}, b={b}")
a, b = b, a
print(f"After swap: a={a}, b={b}")
# Assign the same value to multiple variables
p = q = r = 0
print(f"p={p}, q={q}, r={r}") # p=0, q=0, r=0
Output:
x=10, y=20, z=30
Before swap: a=5, b=10
After swap: a=10, b=5
p=0, q=0, r=0
a, b = b, a works because Python evaluates all expressions on the right side first, then assigns them all at once.
Common Use Cases
- Game player stats: Health, score, level are all stored in variables, updated as the game progresses.
- E-commerce price calculation: Unit price, quantity, discount, shipping — all variables. The program calculates the final price.
- Configuration management: DB addresses, API keys, site names stored in variables — change one place and the whole program is affected.
❓ FAQ
= mean "equals"? Why isn't it like math?= is the assignment operator — it means "store the value on the right into the variable on the left." It's an instruction, not a declaration of equality. To check if two values are equal, use == (two equals signs). One of the most common beginner mistakes is using = instead of == in conditions.
⚠️ Q: Can I use Chinese characters as variable names? Python 3 supports it, right? A: Technically Python 3 does support Chinese variable names (e.g., 姓名 = "Zhang San"), but it's strongly discouraged. Most programming tools, libraries, and code snippets use English names. Mixing languages looks odd and creates communication barriers in international teams. Stick to English variable names.
Q: Why is float imprecise? Why does 0.1 + 0.2 equal 0.30000000000000004? A: This isn't Python's fault — it's a fundamental limitation of how computers store floats in binary. Just as decimal can't precisely represent 1/3 = 0.333..., binary can't precisely represent 0.1 and 0.2. For precise calculations (like currency), use the decimal module instead of float.
Q: What's the difference between None, 0, and empty string ""? A: None means "nothing" or "no value exists." It's different from 0, "", and False. 0 is a number, "" is an empty string, False is a boolean false — they all "exist" but happen to represent emptiness. None means no container at all. Think of "" as an empty bowl, while None means there's no bowl.📖 Summary
- Variables are names for data, assigned with
=, values can change at any time - Variable names can only contain letters, digits, and underscores; can't start with digits or be keywords
- Python has 5 basic types:
int,float,str,bool,NoneType - Python is dynamically typed — same variable can hold different types, but consistency is recommended
type()checks a variable's data type- f-strings use
f"xxx{variable}"to embed variables and expressions in strings
📝 Exercises
-
Basic (Difficulty ⭐): Define variables
city,temperature,is_sunnyfor your city name, today's temperature (float), and whether it's sunny (bool). Useprint()to output a complete sentence. -
Intermediate (Difficulty ⭐⭐): Define two integer variables
minutesandhours. Converthoursto minutes, addminutes, and output the total. For example,hours=2, minutes=15should output135minutes. Hint: 1 hour = 60 minutes. -
Challenge (Difficulty ⭐⭐⭐): Without using a temporary variable, swap three variables in a circular shift:
a → b → c → a(a gets b's original value, b gets c's, c gets a's). Hint: The core idea isa, b, c = b, c, a.



