Python: Zero to Hero
Home/The Foundation
Share

Chapter 2: Variables, Numbers, and Text

In Chapter 1 you made Python print a message. That's a start, but it's a fixed message — the same every time. Real programs need to remember things: a user's name, a price, a score, a date. That's what variables are for.

By the end of this chapter you'll know how to store text and numbers, name them properly, check what type of data you have, and do some basic things with strings. Everything from here on uses these ideas, so let's get them solid.

What is a Variable?

A variable is a name that holds a value.

Think of it like a labeled box. You write a name on the outside (say, age), and you put something inside (say, 25). Whenever you say age in your program, Python opens that box and hands you 25.

age = 25
print(age)

Output:

25

The = sign is called the assignment operator. It means "put this value into this name." The name goes on the left, the value on the right.

You can change what's in the box at any time:

age = 25
print(age)

age = 26
print(age)

Output:

25
26

Python just overwrites the old value. The variable age now holds 26.

In plain English: A variable is a name you choose. You decide what to store under that name, and you can change it whenever you want.

Your turn: Create a variable called score, put the number 100 in it, and print it. Then change score to 95 and print it again. You should see both numbers.

Naming Rules and Conventions

You can name a variable almost anything — but there are rules, and there are habits that make your code easier to read.

The rules (Python enforces these):

  • Names can contain letters, numbers, and underscores (_).
  • Names cannot start with a number.
  • Names cannot have spaces.
  • Names are case-sensitive: score, Score, and SCORE are three different variables.
first_name = "Maya"   # valid
score2 = 100          # valid — number at the end is fine
2score = 100          # INVALID — starts with a number
my score = 100        # INVALID — spaces not allowed

The conventions (good habits):

  • Use snake_case: all lowercase, words separated by underscores.
    • Good: user_name, total_price, number_of_students
    • Avoid: UserName, totalPrice, NumberOfStudents (those styles exist in Python but are used for other things — you'll see this in the OOP chapters)
  • Use descriptive names. age is better than a. monthly_salary is better than ms.
  • Avoid single letters except in short loops (more on that in Chapter 5).
# Hard to read
x = "Ravi"
y = 28
z = 55000.0

# Easy to read
employee_name = "Ravi"
employee_age = 28
monthly_salary = 55000.0

Both versions work. The second one tells you what the values mean without any guesswork.

Your turn: Write three variables using snake_case — one for a person's name, one for their city, and one for their age. Print all three on one line using commas inside print().

Storing Numbers: Integers and Floats

Python has two main types of numbers.

Integers are whole numbers — no decimal point.

apples = 5
temperature = -3
year = 2026

Floats are numbers with a decimal point.

price = 2.99
height = 1.75
pi = 3.14159

You don't have to declare which type you want. Python figures it out from the value you assign.

whole = 10
decimal = 10.0

print(whole)    # 10
print(decimal)  # 10.0

Even though both hold "ten," they are different types. 10 is an integer. 10.0 is a float. This matters sometimes — you'll see why in the next chapter.

Large numbers: Python lets you use underscores as visual separators in big numbers. It doesn't change the value — it just makes them easier to read.

population = 1_400_000_000
distance_km = 384_400

print(population)    # 1400000000
print(distance_km)   # 384400

Negative numbers: Put a minus sign in front.

temperature = -18
bank_balance = -500

Your turn: Create a variable for the price of a coffee (a float), the number of coffees you drink per week (an integer), and the year you were born (an integer). Print all three.

Storing Text: Strings

Text in Python is called a string. You create a string by wrapping text in quotes — single or double, both work.

first_name = "Priya"
last_name = 'Sharma'

print(first_name)   # Priya
print(last_name)    # Sharma

Joining strings together is called concatenation. Use the + operator.

first_name = "Priya"
last_name = "Sharma"
full_name = first_name + " " + last_name

print(full_name)   # Priya Sharma

Notice the " " in the middle — that's a string with just a space. Without it you'd get PriyaSharma.

Printing variables and text together:

The easiest way in modern Python is an f-string (short for "formatted string"). Put an f before the opening quote, then use {} to drop a variable right into the text.

name = "Carlos"
age = 31

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Carlos and I am 31 years old.

The {} is a placeholder. Python replaces it with the variable's value at the moment the line runs. This is clean, readable, and the way most professional Python code is written today.

You can also use commas in print() — Python adds a space between each item:

name = "Carlos"
age = 31

print("My name is", name, "and I am", age, "years old.")

Output:

My name is Carlos and I am 31 years old.

Both approaches give the same output here. F-strings are more flexible for complex formatting, so get into the habit of using them.

Your turn: Create variables for your name and your favorite food. Use an f-string to print a sentence like: My name is ___ and my favorite food is ___.

Escape Sequences and Special Characters

Sometimes you need to put special characters inside a string — a newline, a tab, or a quote mark. You do this with escape sequences: a backslash \ followed by a letter.

Escape What it does Example
\n New line "Line 1\nLine 2"
\t Tab (indent) "Name:\tCarlos"
\\ A literal backslash "C:\\Users\\file.txt"
\" A literal double quote inside double quotes "He said \"hello\""
\' A literal single quote inside single quotes 'It\'s fine'
print("Line 1\nLine 2\nLine 3")

Output:

Line 1
Line 2
Line 3
print("Name:\tCarlos\nAge:\t31")

Output:

Name:   Carlos
Age:    31

Raw strings: If you don't want escape sequences processed — for example, when writing file paths on Windows — put an r before the opening quote.

path = r"C:\Users\Carlos\Documents"
print(path)

Output:

C:\Users\Carlos\Documents

Without the r, Python would try to interpret \U, \C, \D as escape sequences and you'd get strange results or an error.

Multiline Strings

Use triple quotes (""" or ''') to write a string that spans multiple lines.

message = """Dear Carlos,

Welcome to Python.
We hope you enjoy the book.

Best,
The Author"""

print(message)

Output:

Dear Carlos,

Welcome to Python.
We hope you enjoy the book.

Best,
The Author

Everything between the triple quotes — including line breaks — is part of the string. This is useful for long messages, documentation, and templates.

Checking the Type of a Variable

You've stored integers, floats, and strings. Python always knows what type each variable is. You can ask it with the built-in type() function.

age = 25
price = 9.99
name = "Maya"

print(type(age))    # <class 'int'>
print(type(price))  # <class 'float'>
print(type(name))   # <class 'str'>
  • int — integer (whole number)
  • float — floating-point number (decimal)
  • str — string (text)

You'll see more types as the book progresses (bool, list, dict, and others), but these three are the ones you'll use most.

Why does type matter? Because Python behaves differently depending on type. Look at this:

print(10 + 5)       # 15  (addition)
print("10" + "5")   # 105 (joining two strings — not math!)

10 (integer) plus 5 (integer) gives you 15. But "10" (string) plus "5" (string) gives you "105" — because joining two strings just sticks them together.

This surprises almost every beginner at least once. Now you know why.

Converting between types: You can convert a value from one type to another using int(), float(), and str().

x = "42"
print(type(x))        # <class 'str'>

y = int(x)
print(type(y))        # <class 'int'>
print(y + 8)          # 50
n = 100
text = str(n)
print("The number is " + text)   # The number is 100

Without str(n), that last line would crash — you can't join a string and an integer with +. The conversion makes it work.

Your turn: Create variables of three different types: one integer, one float, one string. Print the type() of each. Then try adding two of them without converting and see the error you get. Read the error message. What does it tell you?

Putting It All Together

Here is a short program that uses everything from this chapter:

# A simple profile program
first_name = "Amara"
last_name = "Osei"
age = 27
height = 1.68
city = "Accra"

full_name = first_name + " " + last_name

print(f"Name:   {full_name}")
print(f"Age:    {age}")
print(f"Height: {height} m")
print(f"City:   {city}")

Output:

Name:   Amara Osei
Age:    27
Height: 1.68 m
City:   Accra

Clean. Readable. Every variable has a descriptive name. The f-strings make the output easy to format.

Your turn: Write your own profile program. At minimum, include: your name (two variables combined), your age, one decimal value (height, weight, shoe size — your choice), and your city. Print it with f-strings.

What You Learned in This Chapter

  • A variable is a name that holds a value. Use = to assign a value.
  • Variable names: lowercase, snake_case, descriptive, no spaces, can't start with a number.
  • Python has two number types: int (whole numbers) and float (decimals).
  • Text is called a string (str). Wrap it in single or double quotes.
  • F-strings (f"... {variable} ...") are the best way to mix text and variables.
  • Escape sequences: \n (newline), \t (tab), \\ (backslash), \" (quote).
  • Triple quotes (""") create multiline strings.
  • type() tells you what kind of data a variable holds.
  • You can convert between types with int(), float(), and str().
  • Python treats 10 + 5 (math) and "10" + "5" (joining text) very differently.

What's Next?

You can now store data. The next step is to do things with it.

In Chapter 3, you'll learn how to do calculations — add, subtract, multiply, divide — and use the results in your programs. You'll also meet some useful built-in tools like abs(), round(), and the math module. If you thought variables were useful, wait until you combine them with math.

Your turn: Before moving on, write a program with at least four variables. Use two numbers, one float, and one string. Print a sentence using f-strings that uses all of them. Run it. If it works, you're ready for Chapter 3.

© 2026 Abhilash Sahoo. Python: Zero to Hero.