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).

PYTHON
# Define a variable named age, storing the number 18
age = 18

When you write age = 18, Python does two things:

  1. Allocates memory space and stores the number 18.
  2. Attaches the label age to that space.

From then on, age represents the number 18 — you can use it in calculations, output, or modify it:

PYTHON
print(age)       # Output 18
print(age + 5)   # Output 23
age = 20         # Change the value — the content of the box changes
print(age)       # Output 20
💡 Tip: Variables are called "variables" because their values can change. First you set 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.

PEP 8 is Python's official style guide, widely followed in the industry:

PYTHON
# Good names (clear at a glance)
total_price = 99.9
student_count = 35

# Bad names (unclear purpose)
a = 99.9
b = 35
💡 Tip: The first rule of good code is "others can understand your intent without comments." Naming variables is the first step. Spending 5 seconds on a good name saves 5 minutes for future you reading the code.


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
PYTHON
# 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():

PYTHON
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:

PYTHON
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).

⚠️ Note: Dynamic typing is flexible, but don't abuse it. In real projects, keep one variable for one type to avoid confusion.


4. More print() Features

We saw print() in Lesson 01. Here are two more useful tricks:

Outputting Multiple Values with Commas

PYTHON
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:

PYTHON
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:

PYTHON
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.

PYTHON
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:

PYTHON
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:

PYTHON
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
💡 Tip: In :.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.

PYTHON
# 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")
▶ Try it Yourself

Output:

TEXT
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.

PYTHON
# 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
▶ Try it Yourself

Output:

TEXT
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
⚠️ Note: + 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:

PYTHON
# 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
▶ Try it Yourself

Output:

TEXT
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.

💡 Tip: This "Pythonic" style looks cool, but overusing it can confuse newcomers. Use in moderation in team projects.


Common Use Cases


❓ FAQ

Q Does = mean "equals"? Why isn't it like math?
A In Python, = 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

  1. Basic (Difficulty ⭐): Define variables city, temperature, is_sunny for your city name, today's temperature (float), and whether it's sunny (bool). Use print() to output a complete sentence.

  2. Intermediate (Difficulty ⭐⭐): Define two integer variables minutes and hours. Convert hours to minutes, add minutes, and output the total. For example, hours=2, minutes=15 should output 135 minutes. Hint: 1 hour = 60 minutes.

  3. 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 is a, b, c = b, c, a.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏