Python Quest

Track 2 · Lesson 2 of 11

Naming and readability

Follow Python's naming rules, write names in snake_case, mark constants in UPPER_CASE and choose names that explain the code.

About 25 minFirst steps3 exercisesFree

You will be able to

  • Tell valid variable names from invalid ones and fix the SyntaxError an invalid name causes
  • Write names in snake_case following Python's style conventions
  • Use UPPER_CASE constants instead of unexplained numbers in calculations
  • Rename vague variables so a program explains itself

Programs are read far more often than they are written — by colleagues, by reviewers and by you, three months later. Compare these two lines:

c = a * b * 0.85
sale_price = unit_price * quantity * DISCOUNT_FACTOR

Python treats them identically. A person does not. The second line tells you what is being calculated without a single comment. This lesson covers the rules Python enforces for names and the conventions Python programmers follow so their code reads like the second line.

The rules (enforced by Python)

A variable name:

  • may contain letters, digits and underscores _;
  • must not start with a digit (2nd_price is invalid, price_2 is fine);
  • may not contain spaces, hyphens or other symbols (total-cost reads as "total minus cost");
  • may not be a keyword — a word with a fixed meaning in Python, such as if, for, class, True, None, import, def, and, or, not;
  • is case-sensitive: price, Price and PRICE are three different names.

Break a rule and the program does not start at all: Python reports a SyntaxError before running any line.

Case matters: these are three separate variables
price = 10
Price = 20
PRICE = 30
print(price, Price, PRICE)

Try it: Rename the first variable to 1price and run it. Python refuses to start and points at the invalid name.

Which of these is a valid Python variable name?

The conventions (followed by Python programmers)

Python's official style guide, PEP 8, recommends:

Kind of nameStyleExample
Ordinary variablessnake_case: lowercase words joined by underscoresunit_price, items_in_cart
ConstantsUPPER_CASE with underscoresVAT_RATE, MAX_SEATS

Python does not check these — UnitPrice = 5 runs fine — but every Python developer expects them, so following them makes your code instantly familiar.

A constant is a value that should not change while the program runs: a tax rate, a delivery fee, the number of seats in a room. Python has no way to lock a variable, so the UPPER_CASE name is a promise to the reader: "don't reassign this". Put constants near the top of the program so they are quick to find and update.

Constants replace unexplained numbers
VAT_RATE = 0.15
SERVICE_FEE = 5

ticket_price = 80
vat_amount = ticket_price * VAT_RATE
amount_due = ticket_price + vat_amount + SERVICE_FEE

print("VAT:", vat_amount)
print("Amount due:", amount_due)

Try it: The VAT rate changes to 10%. Change one line and run it again — every calculation that uses VAT_RATE updates.

An unexplained number in the middle of a calculation, such as 0.15 or 5, is often called a magic number: it works, but nobody can tell what it means or where else it is used. Naming it fixes both problems.

Choosing meaningful names

  • Say what the value is: hours_worked, not h or num.
  • Include the unit when it matters: weight_kg, duration_minutes.
  • Avoid names of Python's built-in functions, such as print, input, sum, max, list, str. They are not keywords, so Python lets you reuse them — and then the original function stops working for the rest of the program.
  • Very short names are fine only where the meaning is obvious from context — x and y for coordinates, for instance.

Predict the output

print_count = 3
total = 5
print("Copies:", print_count * total)

Guided practice · ●difficulty 1 of 5 · about 5 min

Use constants for VAT and delivery

An online bakery charges 15% VAT on the order subtotal, then adds a flat delivery fee of 25 SAR (no VAT on delivery). The starter reads the subtotal as a number into subtotal — the tests type the value for you.

  1. Create two constants at the top: VAT_RATE = 0.15 and DELIVERY_FEE = 25.
  2. Calculate vat_amount (the subtotal times the VAT rate).
  3. Calculate total (subtotal + VAT + delivery fee).
  4. Print two lines. For a subtotal of 100:
VAT: 15.0
Total: 140.0

Use the constant names in your calculations, not the numbers 0.15 and 25.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Challenge · ●●difficulty 2 of 5 · about 7 min

Rename a payroll calculation

This payroll program works, but nobody can tell what a, b, c, d and e mean, and the tax rate 0.1 is a magic number. Rewrite it with meaningful names without changing what it prints:

OldNew name
a (first input)hours_worked
b (second input)hourly_rate
cgross_pay
0.1a constant TAX_RATE
dtax
enet_pay

None of the old one-letter names should remain. For the input 40 then 52.5 the output stays:

Gross pay: 2100.0
Tax: 210.0
Net pay: 1890.0

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Debugging · ●●difficulty 2 of 5 · about 5 min

Fix the names that stop a program

A gym's membership program won't even start: pressing Run shows a SyntaxError. It should read the second payment and the total due (the tests type both numbers for you) and print how much is left:

Plan: Premium
Remaining: 750

(for the input 450 then 1200).

Three names break Python's naming rules. Rename them to second_payment, total_due and plan_class, updating every line that uses them.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Summary

  • Names may use letters, digits and underscores, can't start with a digit and can't be keywords; breaking a rule is a SyntaxError.
  • Names are case-sensitive: total, Total and TOTAL are three different variables.
  • Write ordinary variables in snake_case and constants in UPPER_CASE, as PEP 8 recommends.
  • Replace magic numbers with named constants defined near the top of the program.
  • Choose names that say what a value is (and its unit), and don't reuse built-in names like print or sum.