smartyfy.mrindigi.com

Python Master Course V2 — 005. Python Variables, Naming Rules & Object References

Module 01 · Python foundations · Lesson 005 / 200

Python Variables, Naming Rules & Object References

Learn to write reliable Python programs by understanding names, values, types, assignments, mutability and readable naming conventions. This lesson moves beyond memorising the equals sign to explain how Python really manages variables.

Difficulty: Beginner → foundational professional concepts · Recommended study: 60–90 minutes plus practice · Prerequisite: Lessons 001–004 (Python installed, first programs and syntax).

In this lesson · 16 sections + self-check
  1. 🎬 Lesson Video · Dedicated Player & Link Area
  2. 1. Learning Objectives
  3. 2. What Is a Variable in Python?
  4. 3. Creating, Reading and Reassigning Variables
  5. 4. Legal Names vs Professional Names
  6. 5. Dynamic Typing — Types Belong to Objects
  7. 6. References, Equality, Identity & Mutability
  8. 7. Multiple Assignment, Unpacking & Swapping
  9. 8. Input, Conversion & Safe Calculations
  10. 9. Guided Real-World Mini-Project — Invoice Summary
  11. 10. Common Errors & Debugging Playbook
  12. 11. Professional Coding Standards
  13. 12. Guided Practice — Type, Predict, Run, Explain
  14. 13. Independent Exercises
  15. 14. Knowledge Check (Try Before Revealing the Key)
  16. 15. Summary & Next Steps
  17. Interactive self-check

🎬 Lesson Video · Dedicated Player & Link Area

Python V2 — 005 | Variables & Naming Rules

Video not uploaded yet. This is the reserved placement for the lesson-specific video player, thumbnail, transcript and external watch link.

Video URL: To be added by the course administrator

Suggested chapters: 00:00 What is a variable? · 08:00 Assignment · 17:00 Naming rules · 28:00 Dynamic typing · 40:00 References & mutability · 55:00 Mini-project.

No video has been claimed or embedded. When a real lesson URL is available, this block can be replaced with the relevant embedded player or link.

1. Learning Objectives

After studying this lesson and completing its tasks, you should be able to:

  1. Create variables, inspect their values, update them and distinguish assignment from mathematical equality.
  2. Apply Python’s identifier rules and professional snake_case, PascalCase and UPPER_SNAKE_CASE conventions.
  3. Explain dynamic typing: a name can refer to an integer, then later to a string, without changing the underlying object’s type.
  4. Use type(), isinstance() and basic type conversion appropriately.
  5. Distinguish equality (==) from object identity (is) at a conceptual level.
  6. Understand how assigning a mutable object to multiple names can cause shared changes.
  7. Use multiple assignment and sequence unpacking safely.
  8. Avoid common professional bugs: shadowing built-ins, case mismatch, unintended aliasing, and converting user input incorrectly.
  9. Build a small, validated invoice-summary program with readable names and predictable results.

Prerequisite check

You should be comfortable opening a Python file, running python filename.py (or python3 filename.py on systems that use that command), writing a print() statement and recognising an indentation error. If not, revise Lesson 004 before proceeding.

2. What Is a Variable in Python?

In everyday speech, a variable is a labeled place where a value is kept. That explanation is a useful starting point, but Python’s more precise model is: a variable name is bound to an object. The name lets your code refer to that object. Assignment changes which object a name refers to; it does not necessarily change an existing object.

student_name = "Ananya"
age = 19
course_name = "Python Master Course"

print(student_name)
print(age)
print(course_name)

Expected output:

Ananya
19
Python Master Course

Read age = 19 as “bind the name age to the integer object representing 19”. You can subsequently read age to obtain that value.

PartMeaningExample
IdentifierThe name used in codestudent_name
Assignment operatorBinds a name to the value of an expression=
ExpressionCode producing a value"Ananya", 18 + 1
ObjectThe runtime value to which a name refersA string, integer, list, etc.

Example 2.1 — Expressions are evaluated before assignment

basic_pay = 30000
allowance = 2500
gross_pay = basic_pay + allowance

print("Gross pay:", gross_pay)

Expected output: Gross pay: 32500. The right-hand expression is evaluated first. The result is then bound to gross_pay.

Example 2.2 — Names are case-sensitive

total = 100
Total = 250

print(total)
print(Total)

Expected output: 100 and 250 on separate lines. Python treats total and Total as different names. Avoid distinctions that differ only in case, because they can confuse readers.

3. Creating, Reading and Reassigning Variables

Python does not require a special declaration keyword for ordinary local variables. A successful assignment introduces a binding in the current namespace. Later assignment to the same name may replace its binding.

Example 3.1 — Updating a total

cart_total = 500
print("Before:", cart_total)

cart_total = cart_total + 150
print("After:", cart_total)

Expected output:

Before: 500
After: 650

The expression on the right uses the previous value of cart_total. This is not an algebraic equation asserting that 500 equals 650: = is assignment. Python also offers += as a concise update operator; you will explore assignment operators in Lesson 012.

Example 3.2 — Predict the execution

score = 10
bonus = 5
score = score + bonus
bonus = 20
print(score, bonus)

Expected output: 15 20. Updating bonus does not retroactively recalculate score; score already refers to the result of the earlier addition.

Example 3.3 — A name must be bound before it is read

# Incorrect if the name has never been assigned:
# print(final_amount)

final_amount = 750
print(final_amount)

Expected output: 750. Removing the comment marker from the first line in a fresh script will raise a NameError. This is different from a name bound to None, which is a real Python value.

4. Legal Names vs Professional Names

Python identifiers can contain Unicode letters, digits and underscores (subject to Python’s identifier rules), but cannot begin with a digit. They must not be Python keywords. Identifiers are case-sensitive. For broadly readable production code, use descriptive ASCII names unless your project has a deliberate reason to use other characters.

NameValid?Why
student_countYesDescriptive snake_case
total2YesDigits allowed after first character
_cacheYesLeading underscore is allowed and suggests internal use
2totalNoBegins with a digit
first-nameNoHyphen is interpreted as subtraction
order totalNoContains a space
classNoReserved keyword

Python’s naming conventions

  • snake_case — conventional for variables and functions: monthly_revenue, customer_id.
  • PascalCase — conventional for classes: InvoiceItem (introduced later).
  • UPPER_SNAKE_CASE — conventional for constants: MAX_ATTEMPTS, GST_RATE. Python does not enforce read-only constants through this naming style.
  • Leading underscore — often communicates a non-public implementation detail; it is not a security mechanism.

Prefer item_price over ip, student_count over sc and is_active over flag when the specific meaning is important. Very short loop indices may be acceptable in small, unambiguous contexts.

Example 4.1 — Verify names and keywords

import keyword

print("class is a keyword:", keyword.iskeyword("class"))
print("student_count is valid:", "student_count".isidentifier())
print("2students is valid:", "2students".isidentifier())

Expected output:

class is a keyword: True
student_count is valid: True
2students is valid: False

Be careful: str.isidentifier() checks identifier form, not whether a string is a reserved keyword. Use keyword.iskeyword() as an additional check when validating generated names.

Example 4.2 — Avoid shadowing built-in functions

# Avoid doing this:
# list = [1, 2, 3]

numbers = [1, 2, 3]
print(len(numbers))
print(sum(numbers))

Expected output: 3 followed by 6. Assigning to list, str, sum, input or id is syntactically legal, but it can hide a useful built-in name within that scope and cause confusing errors later.

5. Dynamic Typing — Types Belong to Objects

Python is dynamically typed: ordinary names are not permanently declared as “integer variables” or “string variables”. Instead, the object currently referenced by a name has a type. A name may later be rebound to an object of another type.

Example 5.1 — Rebinding to a different type

item = 25
print(item, type(item).__name__)

item = "Notebook"
print(item, type(item).__name__)

item = 25.5
print(item, type(item).__name__)

Expected output:

25 int
Notebook str
25.5 float

This flexibility is valuable, but mixing unrelated meanings under one name can make code hard to maintain. In production, use distinct names where possible, such as quantity and product_name.

Example 5.2 — Common foundational object types

quantity = 3                 # int
unit_price = 49.95           # float
product = "Pen"              # str
available = True             # bool
discount = None              # NoneType
stock_levels = [5, 8, 2]     # list

for value in (quantity, unit_price, product, available, discount, stock_levels):
    print(type(value).__name__)

Expected output:

int
float
str
bool
NoneType
list

None represents the absence of a value in many Python interfaces; it is not interchangeable with 0, False or an empty string.

Example 5.3 — isinstance() and the bool caveat

print(isinstance(42, int))
print(isinstance("42", int))
print(isinstance(True, int))

Expected output: True, False, True. In Python, bool is a subclass of int. Type checks must reflect your application’s intent; do not assume isinstance(x, int) excludes Boolean values.

Example 5.4 — Type hints improve communication; they do not enforce types at runtime

customer_count: int = 5
print(customer_count)

# Python allows this assignment at runtime; a type checker can flag it.
customer_count = "five"
print(customer_count)

Expected output: 5 then five. Type hints serve tooling and documentation; they are not automatic runtime validation. Later lessons cover type hints and static analysis in depth.

6. References, Equality, Identity & Mutability

This is the most important conceptual upgrade in this lesson. Two names may refer to the same object, or to two different objects whose contents compare equal. Equality asks whether values are equivalent; identity asks whether two references point to the same object.

Example 6.1 — Equality is not the same as identity

first_list = [1, 2, 3]
second_list = [1, 2, 3]
alias = first_list

print(first_list == second_list)
print(first_list is second_list)
print(first_list is alias)

Expected output:

True
False
True

The two independently created lists have equal contents but are distinct list objects. alias refers to the exact same list object as first_list. Do not use is instead of == for ordinary value comparisons. A common appropriate identity check is value is None.

Example 6.2 — Shared mutable object: a real source of bugs

primary_tasks = ["read"]
shared_tasks = primary_tasks

shared_tasks.append("practice")
print(primary_tasks)
print(shared_tasks)

Expected output:

['read', 'practice']
['read', 'practice']

Both names refer to the same mutable list. Calling append() changes that one object, so both names observe the updated contents. Assignment does not copy the list.

Example 6.3 — Make a separate list when independence is required

primary_tasks = ["read"]
independent_tasks = primary_tasks.copy()

independent_tasks.append("practice")
print(primary_tasks)
print(independent_tasks)

Expected output:

['read']
['read', 'practice']

list.copy() makes a shallow copy. If the list contains nested mutable objects, inner objects may still be shared; deep copying will be explained in a later collections lesson.

Example 6.4 — Rebinding an immutable integer is different from mutating a list

original = 10
other_name = original

other_name = other_name + 1
print(original, other_name)

Expected output: 10 11. Integers are immutable. The addition produces a new integer result and rebinds other_name, leaving original unchanged.

Visual reference model

StatementConceptual effect
a = [1, 2]Name a → list object L
b = aNames a and b → the same list L
b.append(3)List L changes to [1, 2, 3]
b = [7]Name b → a new list; a still → L

Advanced note: Python may reuse certain immutable objects as an implementation detail. Never write a program that relies on is comparisons between separately constructed numbers or strings.

7. Multiple Assignment, Unpacking & Swapping

Python can bind several names on one statement. This helps when related values belong together, but unpacking requires the right number of items unless starred unpacking is used.

Example 7.1 — Parallel assignment

product_name, quantity, unit_price = "Notebook", 4, 80

print(product_name)
print(quantity)
print(unit_price)

Expected output: Notebook, 4 and 80 on successive lines.

Example 7.2 — Safe swapping

left = "A"
right = "B"

left, right = right, left
print(left, right)

Expected output: B A. Python evaluates the right-hand side and then performs the unpacking; you do not need an explicit temporary variable for this simple swap.

Example 7.3 — Starred unpacking

first, *middle, last = (10, 20, 30, 40, 50)
print(first)
print(middle)
print(last)

Expected output:

10
[20, 30, 40]
50

Common error: mismatched unpacking

# This fails with ValueError:
# x, y = (10, 20, 30)

Provide matching target names, choose starred unpacking, or extract the specific elements you need. Avoid hiding this kind of error with a broad bare except.

8. Input, Conversion & Safe Calculations

Interactive input is text. A program must explicitly convert that text when numeric arithmetic is intended. Professional input handling anticipates unexpected values rather than assuming everyone enters valid digits.

Example 8.1 — Demonstrate why conversion matters

typed_quantity = "4"
typed_extra = "2"

print(typed_quantity + typed_extra)
print(int(typed_quantity) + int(typed_extra))

Expected output:

42
6

Concatenating strings produces a different result from adding integers. A genuine input() call returns a string (or raises an input-related exception under exceptional execution conditions).

Example 8.2 — Error-aware conversion

raw_quantity = "12"

try:
    quantity = int(raw_quantity)
    if quantity < 0:
        print("Quantity cannot be negative.")
    else:
        print("Valid quantity:", quantity)
except ValueError:
    print("Enter a whole number.")

Expected output: Valid quantity: 12. Change raw_quantity to "twelve" and the friendly error branch runs. The full exception-handling topic appears later; for now, observe why input validation is useful.

Precision note

Binary floating-point numbers such as 0.1 cannot always represent decimal currency values exactly. For financial applications, Python’s decimal.Decimal is usually preferable to float. We will apply it in the mini-project.

9. Guided Real-World Mini-Project — Invoice Summary

Scenario: A training centre wants a basic invoice for course materials. We will use meaningful variable names, validate input, perform precise decimal arithmetic, and display a tidy result. This example is runnable in Python 3 using only its standard library.

Requirements

  1. Store a customer name, item description, quantity and unit price.
  2. Reject invalid or negative numeric input.
  3. Calculate a subtotal, a configurable tax amount and the grand total.
  4. Show amounts with exactly two decimal places.
  5. Avoid sharing unrelated responsibilities under the same variable name.

Complete runnable code — lesson_005_invoice.py

from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

CUSTOMER_NAME = "Ananya"
ITEM_NAME = "Python practice notebook"
TAX_RATE = Decimal("0.05")  # Example rate only; not legal tax advice.

quantity_text = "3"
unit_price_text = "149.50"

try:
    quantity = int(quantity_text)
    unit_price = Decimal(unit_price_text)

    if quantity <= 0:
        raise ValueError("Quantity must be greater than zero.")
    if not unit_price.is_finite() or unit_price < 0:
        raise ValueError("Unit price must be finite and non-negative.")

    subtotal = unit_price * quantity
    tax_amount = (subtotal * TAX_RATE).quantize(
        Decimal("0.01"), rounding=ROUND_HALF_UP
    )
    grand_total = subtotal + tax_amount

    print("=== SMARTYFY INVOICE ===")
    print(f"Customer: {CUSTOMER_NAME}")
    print(f"Item: {ITEM_NAME}")
    print(f"Quantity: {quantity}")
    print(f"Unit price: {unit_price:.2f}")
    print(f"Subtotal: {subtotal:.2f}")
    print(f"Tax: {tax_amount:.2f}")
    print(f"Grand total: {grand_total:.2f}")

except (ValueError, InvalidOperation) as error:
    print(f"Invalid invoice data: {error}")

Expected output:

=== SMARTYFY INVOICE ===
Customer: Ananya
Item: Python practice notebook
Quantity: 3
Unit price: 149.50
Subtotal: 448.50
Tax: 22.43
Grand total: 470.93

Walkthrough

  1. from decimal import ... imports tools to represent decimal money-like values and round in a clearly specified manner.
  2. CUSTOMER_NAME, ITEM_NAME and TAX_RATE are written in uppercase to communicate constant-like configuration values. Python does not enforce immutability of these names.
  3. quantity_text and unit_price_text represent incoming text; preserving “_text” in the names clarifies their initial types.
  4. int() and Decimal() convert validated representations into objects suitable for arithmetic.
  5. The validation prevents zero/negative quantities, negative prices and non-finite prices, including special decimal values such as NaN.
  6. subtotal represents an intermediate result. tax_amount is rounded to two decimal places using the explicitly selected rounding mode; the final total adds the rounded tax.
  7. The :.2f formatting specification prints two decimal places. An f-string inserts expressions into readable output.
  8. The narrowly scoped exception handler provides a useful error message rather than crashing on common invalid inputs.

Production consideration: Tax calculations vary by jurisdiction and product category. The 5% figure is illustrative, not a recommendation for any actual invoice. Real systems need documented business rules, tested rounding and data validation.

Mini-project extensions

  • Change the quantity to 5 and calculate the expected total before executing the code.
  • Set the unit price to a negative value and confirm the validation message.
  • Refactor a second item into the program without inventing vague names such as x or data1.
  • Consider why converting to float would be a weaker choice for precise billing.

10. Common Errors & Debugging Playbook

SymptomLikely causeReliable fix
NameErrorName read before assignment or misspelledCheck spelling, capitalization and execution order
SyntaxError: invalid decimal literal or invalid syntaxIdentifier begins with a digit or has invalid charactersRename to item2, item_price etc.
TypeError during arithmeticMixing strings with incompatible numeric operationsConvert/validate types deliberately
Unexpected list changesTwo names share one mutable listCopy the collection if independent state is required
Built-in function “not callable”Variable shadows a built-in such as listRename the variable; restart the session if needed
ValueError in unpackingItem count doesn’t match target countUse matching targets or starred unpacking
Incorrect monetary centsBinary floating-point or wrong rounding policyUse Decimal and explicit business rules

Practical debugging sequence

  1. Read the exception name and traceback line number, not just the final error text.
  2. Identify the current type of the value using a temporary print(type(value).__name__).
  3. Verify the exact spelling and case of the name; inspect nearby assignments.
  4. Reduce the problem to a five-line example if behaviour is surprising.
  5. Check whether two names point to the same mutable object.
  6. Fix the root cause and rerun the test case that originally failed.

11. Professional Coding Standards

  • Prefer explicit, domain-relevant identifiers: account_balance communicates intent better than a.
  • Follow PEP 8 naming conventions and keep spelling consistent throughout a file.
  • Use names for one clear concept; avoid rebinding a monetary amount to an unrelated text message.
  • Avoid mutable shared state unless its sharing is intentional and documented.
  • Distinguish “not set” (None) from empty or zero when the difference matters.
  • Do not use is to compare arbitrary numbers or strings for equality.
  • Do not use ordinary floats for high-stakes monetary accounting without a deliberately justified numeric model.
  • Use small, testable pieces of code. The later Functions, OOP and Testing modules will build on these fundamentals.

12. Guided Practice — Type, Predict, Run, Explain

Task A — Predict before executing

first = [10]
second = first
second = [20]
print(first, second)

Question: Will changing the binding of second modify first? Why?

Task B — Fix the naming problems

# Identify the issues; do not execute these invalid lines:
# 4students = 40
# learner-name = "Meera"
# class = "Python"
# list = [1, 2, 3]

Write clear replacements that follow conventions and avoid hiding built-in names.

Task C — Inspect the difference

a = [7, 8]
b = a
c = a.copy()

print(a == b)
print(a is b)
print(a is c)
print(a == c)

Explain all four results using the ideas of equality, identity and copying.

Task D — Input conversion

Ask a learner for a non-negative integer number of practice problems completed. Convert the string, reject invalid values, and print a meaningful message. Use try/except ValueError rather than a broad exception handler.

Task A answer

Hint

Separate rebinding from mutation.

Show answer and explanation

The output is [10] [20]. Rebinding second to a new list leaves first referring to the original [10] list. No list was mutated.

Task B answer

Hint

Use identifiers that describe their roles.

Show answer and explanation

Suitable replacements are student_count = 40, learner_name = "Meera", course_title = "Python", and numbers = [1, 2, 3]. The first three repair invalid identifiers; the last avoids hiding the built-in list.

Task C answer

Hint

Test value equality independently of object identity.

Show answer and explanation

The four results are True, True, False, True. b aliases a. c is a distinct shallow copy with equal elements. Equal contents do not require the same object.

Task D answer

Hint

Catch conversion errors, then check the range.

Show answer and explanation

Convert with int(), handle ValueError, and reject a result below zero before accepting it. For example, valid text “3” converts to 3; “three” fails conversion; “-1” converts successfully but violates the nonnegative contract. The full interactive version belongs in a local script so you can test all three inputs.

13. Independent Exercises

1. Create variables for a person’s name, city, age and enrolment status; print a formatted introduction.

Hint

Use descriptive names and an actual Boolean for status.

Show answer and explanation

The f-string inserts each current value into the introduction. The status is True, not the nonempty string “True”.

person_name = "Asha"
city = "Hyderabad"
age = 20
is_enrolled = True
print(f"{person_name}, {age}, from {city}; enrolled: {is_enrolled}")

2. Calculate total study minutes from hours and minutes using clear names.

Hint

One hour contains 60 minutes.

Show answer and explanation

Multiply hours by 60 before adding minutes. With one hour and 45 minutes, the result is 105. Assume valid nonnegative integer inputs for this exercise.

hours = 1
minutes = 45
total_study_minutes = hours * 60 + minutes
print("Study minutes:", total_study_minutes)

3. Identify which of these are valid: order_total, total-value, _temp, 9lives, False, name2.

Hint

Check the first character, operators, and keywords.

Show answer and explanation

Valid: order_total, _temp, and name2. Invalid: total-value contains a hyphen, 9lives begins with a digit, and False is a keyword.

4. Demonstrate case sensitivity with two variables that differ only in capitalization, then rewrite the example using clearer names.

Hint

Capitalization creates distinct bindings, but roles make better names.

Show answer and explanation

name = "Asha" and Name = "Ravi" refer to different names. If their roles are learner and tutor, use learner_name and tutor_name so a reader need not memorize capitalization.

5. Show the type of each value in (None, True, 12, 12.5, "12", [12]).

Hint

Inspect each object, not a permanently typed name.

Show answer and explanation

The types in order are NoneType, bool, int, float, str, and list. The text “12” is still a string, and [12] is a list containing an integer.

values = (None, True, 12, 12.5, "12", [12])
for value in values:
    print(type(value).__name__)

6. Create an alias for a list, mutate it, and explain the changed output. Then repeat using .copy().

Hint

Mutating a shared object differs from copying it.

Show answer and explanation

The first append changes the shared list, so both names see [1, 2, 3]. In the second example, the copied outer list changes while the original remains [1, 2]. These flat lists do not demonstrate nested-object sharing.

original = [1, 2]
alias = original
alias.append(3)
print(original, alias)

original = [1, 2]
copied = original.copy()
copied.append(3)
print(original, copied)

7. Swap the values of first_city and second_city without a temporary name.

Hint

The right side is evaluated before assignment.

Show answer and explanation

Tuple-style unpacking binds each name to the other city’s original value. The output is Mumbai Hyderabad.

first_city = "Hyderabad"
second_city = "Mumbai"
first_city, second_city = second_city, first_city
print(first_city, second_city)

8. Unpack ("Python", 200, "Advanced") into three descriptive variable names.

Hint

Match the number of values with the number of names.

Show answer and explanation

Use three descriptive names. Unpacking a different number of values without a starred target would raise ValueError.

course_title, lesson_count, course_level = ("Python", 200, "Advanced")
print(course_title, lesson_count, course_level)

9. Correct a bug caused by assigning a string value to a variable previously used as a numeric counter.

Hint

Keep an external text value separate until conversion succeeds.

Show answer and explanation

If count becomes “5”, count + 1 raises TypeError. Convert valid text with int() and handle ValueError for malformed input. Avoid rebinding a numeric counter to presentation text.

count_text = "5"
count = int(count_text)
count += 1
print(count)

10. Write a small price calculator using Decimal and a clear, well-documented rounding decision.

Hint

Build Decimal values from strings and round at a stated stage.

Show answer and explanation

This educational calculator assumes a finite nonnegative price and positive integer quantity. It rounds the final line total to two decimal places using HALF_UP; 19.995 times 2 yields 39.99. A real system should enforce those contracts.

from decimal import Decimal, ROUND_HALF_UP

unit_price = Decimal("19.995")
quantity = 2
line_total = (unit_price * quantity).quantize(
    Decimal("0.01"), rounding=ROUND_HALF_UP
)
print(f"Line total: {line_total:.2f}")

Stretch task: Extend the invoice project to display a discount and final amount. Keep every intermediate value in a descriptively named variable and test at least three input combinations.

14. Knowledge Check (Try Before Revealing the Key)

1. What does the statement result = 5 + 7 do?

Hint

Evaluate the right side before binding the left name.

Show answer and explanation

Python adds 5 and 7, producing the integer 12, then binds result to that object. Assignment does not display it; use print(result) to see it.

2. Does Python bind a type permanently to an ordinary variable name?

Hint

Distinguish a name from the object it refers to.

Show answer and explanation

No. Objects have types. A name can be rebound from an integer to a string, but later operations must still suit the current object. Consistent types make a program easier to understand and check.

3. Is student-count a legal variable name?

Hint

A hyphen is subtraction syntax.

Show answer and explanation

No. Use student_count. Python treats student-count as an expression involving subtraction, not one identifier.

4. Which naming style is customary for ordinary functions and variables?

Hint

Separate words without hiding their role.

Show answer and explanation

Use snake_case, for example order_total. Descriptive names help a reader understand the value’s role; avoid names that hide built-ins such as list.

5. What is the difference between == and is?

Hint

Equal values can be separate objects.

Show answer and explanation

== checks equality; is checks object identity. Two separately created lists can be equal but have different identities. Use is None for the sentinel and == for ordinary value comparisons.

6. Does b = a copy a list stored in a?

Hint

Assignment binds another name to the same object.

Show answer and explanation

No. Both names refer to the same list. Mutating it through either name affects that shared object. a.copy() makes a shallow copy: the outer list is new, but nested objects are still shared.

7. Why does "3" + "4" produce "34"?

Hint

Examine the operand types.

Show answer and explanation

They are strings, so + concatenates their characters. Convert valid numeric text first if the required result is arithmetic: int("3") + int("4") gives 7.

8. What is the distinction between assigning None and never assigning a name?

Hint

None is a value; an unbound name has no value to read.

Show answer and explanation

value = None defines the name and intentionally records an absence sentinel. Reading a name that has never been assigned in that execution raises NameError. Test an assigned sentinel with is None.

9. What would a type checker potentially report about count: int = "five"?

Hint

Annotations describe expectations rather than force conversion.

Show answer and explanation

A type checker can report that a string is incompatible with int. Normal Python execution does not automatically convert or reject it merely because of that annotation. Runtime validation is still needed at external boundaries.

10. Why is Decimal("0.1") often preferable to 0.1 for money-like arithmetic?

Hint

Start from decimal text and choose a rounding rule.

Show answer and explanation

Decimal("0.1") represents that decimal value exactly. Binary float typically approximates it. Decimal arithmetic still needs adequate precision, finite-value checks, and an explicit rounding policy for monetary results.

15. Summary & Next Steps

You now know that Python names refer to objects rather than acting as permanent typed boxes. You can write clear, legal identifiers, update values, recognise type changes, distinguish equality from identity, avoid accidental shared mutation, unpack multiple values and validate incoming text. The guided invoice program showed how these foundational habits lead directly to dependable real-world code.

What to revise before moving on: the name/object binding model, list aliasing vs copying, and dynamic typing. Being able to explain these aloud is a strong sign of understanding.

Next lesson — 006. Numbers and Numeric Types: integers, floats, numeric conversion, division, precision, rounding, overflow considerations and real-world numeric calculations.

Apply what you learned

Interactive self-check

Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.

1. What does x = 5 do?
2. After a = [1]; b = a; b.append(2), what is a?
3. Which operator compares values for equality?
4. Do type hints enforce runtime types by themselves?
5. Why avoid a variable named list?

This is a practice quiz. Results are saved on this browser when storage is available.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.