Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Variables & Data Types

Variables & Data Types 17 minA variable is a name bound to an object, such as a number or a piece of text. An object’s type determines which operations it supports.

A variable is a name bound to an object, such as a number or a piece of text. An object’s type determines which operations it supports.

Track assignments, inspect basic types and see why rebinding one name does not change every other name.

A balance changes after a trip, while an earlier balance must remain available for comparison. Follow those two values to learn what assignment changes. Then distinguish the numeric value from the text used to display it. You need only the assignment and print statements from Basic Syntax.

Three steps with name tags: fare is tied to a box holding 120, then old is tied to the same box, then fare = fare + 30 makes a new box holding 150 and moves only the fare tag there, while old stays on 120

Track a metro card balance

A metro card starts with ₹200. Each trip takes money off, and a recharge adds some back. One name, updated over and over:

python

Read balance = balance - 35 from the right: compute 200 - 35, then bind balance to the resulting integer 165. This does not change the integer 200 itself. A variable is a name bound to an object; the object has the type, and assignment can later rebind the name. There is no separate variable-declaration statement required here.

Now preserve the old balance under a second name, then take the trip. Assignment does not copy an object; it gives another name to the same value:

What does this print?
balance = 200
before = balance
balance = balance - 35
print(before, balance)

For ordinary ASCII names, use letters, digits and _, do not begin with a digit, and avoid reserved keywords such as class. Python also permits many Unicode identifier characters. A hyphen means subtraction, not part of a name:

broken — fix itSyntaxError

Run it, read the error, and rename the variable so it prints 200.

Python style is snake_case: lower case with underscores, like card_balance or trips_today. Pick names that still make sense next month: balance beats b.

You can also tie several names in one line, which gives a neat way to swap:

python

Preparing this topic’s interactive investigation…

Read a cricket scorecard

A scorecard mixes every basic type. type() tells you which one a value is:

python

The float representation approximates many decimal fractions; 5.74 is not stored as an exact base-ten fraction. None is a value of type NoneType, not a type name. Use repr(value) and type(value) when display alone is ambiguous: print("12") and print(12) look the same.

The type determines what + means. A scoreboard app reads the score from a web page, so it arrives as text, and a boundary gets added:

What does this print?
score = "84"
score = score + "4"
print(score)

Mix a number with text and Python refuses instead of guessing, which is a good thing: "84" + 4 is a TypeError. (Turning text into numbers properly is the whole of the type casting lesson.)

Numbers have their own rule: mixing int and float gives a float, and / gives a float for these integer operands, even when it divides exactly:

python

A scorecard also holds whole collections: the batting order, the final score pair, each player's runs, the set of bowlers used. Python has a type for each, and you'll get a full lesson on them later:

python

Show a price on the menu

A café app stores the price of a sandwich as the number 12.5. The menu must show exactly two decimals. A plain f-string won't do it, and neither will round():

What does this print?
price = 12.5
print(f"₹{price}", round(price, 2))

Put :.2f after the value inside the braces: "fixed point, 2 decimals". It pads and rounds, and it builds new text. The number itself never changes:

step through it
1price = 12.5
2plain = f"₹{price}"
3menu = f"₹{price:.2f}"
4long = f"₹{3.14159:.2f}"
5print(plain, menu, long, price)

At the end price is still 12.5. Keep the number for sums, and format only when you display it. You'll often see that promise written on the function itself as a type hint. Hints describe what goes in and what comes out; Python does not enforce these argument and return types automatically:

def menu_price(amount: float) -> str:
    return f"₹{amount:.2f}"

Traps worth knowing

  • print() shows a value but returns None, so x = print("hi") leaves x as None.
  • bool supports integer arithmetic: True + True is 2. Boolean values still communicate a yes/no intent, not an amount.
  • "5", 5 and 5.0 look alike and are three different types. When a result surprises you, print type(x) first.

A value can be absent without a name being absent

price = None binds a real value meaning “no price supplied” in this program. price = 0 can mean a known, free item. Leaving price unassigned is a third case: reading that name raises NameError. Choosing None is a contract between the producer and consumer; Python does not decide what it means for your application.

For built-in numeric types, bool is a subclass of int, so arithmetic can use True as 1 and False as 0. Still name flags as questions, such as is_paid, and amounts as quantities. A payment of True is rarely the value you meant, even though some arithmetic accepts it.

Try this without copying the earlier example: preserve an original score, apply two updates to the current score, and format only the final display. Explain which names refer to numbers and which refer to text. Your original score should remain available for comparison.

Quick practice

What does this print?
a = 10
b = a
a = 99
print(b)
What does this print?
print(type(10 / 2).__name__)
broken — fix itSyntaxError

Rename the variable so the score prints.

What does this print?
total = 7
Total = total + 1
print(total)

🎯 Your turn

Write format_money(amount). It turns a number into a price string with a $ and exactly two decimals:

  • format_money(12.5) → "$12.50"
  • format_money(84) → "$84.00"

Hint: f"${amount:.2f}". The $ sits outside the braces, and :.2f pads and rounds for you.

Press ▶ Run, try the Live App chips, then ✓ Check.

Your task
Build format_money(amount). It turns a number into a price string with a $ and exactly two decimals. Example: format_money(12.5) → "$12.50".
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — format_money(): Turns every number into a clean $ price on screen.
Scenario The soup is stored as 12.5 in the database, but the receipt must read $12.50. This function formats every amount on screen.
format_money.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
format_money(amount) → strFormat a number as a $ price with 2 decimals.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.