Understand how Python names refer to typed values, convert and validate external text, model absence with None, and communicate contracts with type hints.
Every Python program works with values: a learner's name, a lesson count, a price, a yes-or-no decision, or the deliberate absence of information. A type describes what a value represents and which operations make sense for it. Learning to recognize types lets you predict results before running code and diagnose mistakes without guessing.
Learning goals
Distinguish a value, its type, and the name that refers to it.
Use int, float, str, bool, and None intentionally.
Inspect values with type and isinstance without using inspection as a substitute for clear design.
Convert external text at the boundary and handle invalid conversion.
Compare values with == and reserve is for singleton identity checks such as is None.
Explain what type hints communicate and what they do not enforce at runtime.
Values, names, and objects
In Python, a variable is best understood as a name bound to an object. The object carries the value and its type; the name lets later statements refer to it. Assignment evaluates the expression on the right, then binds the name on the left. A name can later be rebound to another object, which is why Python is dynamically typed.
PYTHON · EDITABLE
completed =4print(completed,type(completed))
completed = completed +1print(completed,type(completed))# Rebinding is legal, but changing meaning is confusing:
completed ="five"print(completed,type(completed))
The core scalar types
An int stores a whole number with arbitrary precision. A float stores an approximate binary floating-point number. A str stores Unicode text. A bool is either True or False. None is the single value of NoneType and represents an intentional absence. These are scalar values because each represents one conceptual piece of data.
Use repr while learning when you need an unambiguous representation: it keeps quotation marks around strings and shows None clearly. type(value).__name__ gives a readable type name. In application logic, isinstance(value, expected_type) is usually more flexible than comparing type(value) directly because it respects compatible subclasses.
Numbers, division, and booleans
Arithmetic preserves or produces types according to the operation. Adding two integers produces an integer, but ordinary division with / produces a float even when the result is mathematically whole. Floor division // rounds down, which differs from merely removing the decimal part for negative numbers. Booleans participate in Python's numeric hierarchy, but treating True as 1 in business calculations usually hides intent.
PYTHON · EDITABLE
print(7+2,type(7+2).__name__)# 9 intprint(8/2,type(8/2).__name__)# 4.0 floatprint(7//2)# 3print(-7//2)# -4: rounds downprint(isinstance(True,int))# True, but do not use bool as a count
Strings and explicit conversion
Text remains text even when it contains digits. Input from forms, command-line arguments, environment variables, and many file formats arrives as strings. Convert once at that boundary, validate the result, and let the rest of the program work with a dependable type. int accepts integer-shaped text; float accepts decimal-shaped text; str creates a textual representation.
int("three") and float("free") raise ValueError because the text cannot be interpreted as the requested number. That failure prevents invalid data from quietly entering a calculation. Catch the error only where you can add useful context or ask for corrected input.
PYTHON · EDITABLE
defparse_quantity(raw:str)->int:try:
quantity =int(raw)except ValueError as error:raise ValueError("Quantity must be a whole number")from error
if quantity <1:raise ValueError("Quantity must be at least 1")return quantity
print(parse_quantity("3"))
None, equality, and identity
None means that a value is absent, unknown, or not yet produced—it is not zero, False, or an empty string. Use value is None and value is not None because None is a singleton. The == operator asks whether values are equal; is asks whether two references point to the exact same object. Most value comparisons need ==.
PYTHON · EDITABLE
coupon_code =Noneif coupon_code isNone:print("No coupon supplied")print(0==False)# True: equal under numeric comparisonprint(0isFalse)# False: distinct objects# Use == for values and `is None` for absence checks.
Truthiness is convenient, but precision matters
Conditions treat several values as false: False, None, numeric zero, and empty collections or strings. Other values are truthy. if not name is useful when empty text and missing text mean the same thing. If zero is a valid quantity or None has a distinct meaning, write an explicit comparison so the program preserves that distinction.
PYTHON · EDITABLE
discount_percent =0
completion_date =Noneif discount_percent ==0:print("No discount")if completion_date isNone:print("Course is not complete yet")
Type hints communicate a contract
Annotations such as raw: str and -> int document the values a function expects and returns. Editors, type checkers, and readers can use them before the program runs. Python itself does not automatically reject a wrong argument merely because it conflicts with a hint; runtime validation is still needed at untrusted boundaries.
PYTHON · EDITABLE
defprogress_label(completed:int, total:int)->str:if total <=0:raise ValueError("total must be positive")
percent = completed / total
returnf"{percent:.0%} complete"print(progress_label(3,12))
Guided practice: normalize an order
Use the runnable notebook below. Predict the output, run it, then test three changes: use an invalid quantity, set coupon_code to SAVE10, and change the unit price. Read the final traceback line when validation fails.
Identify which values begin as external text.
Convert and validate those values before calculating.
Keep the optional coupon as None until a code is supplied.
Format the number only at the presentation step.
Explain why the function returns a string even though its intermediate result is numeric.
Common mistakes to diagnose
Concatenating numeric-looking strings instead of converting them.
Calling bool on user-entered text and assuming the word False becomes False.
Using is for ordinary string or number equality.
Treating None, zero, and an empty string as interchangeable.
Changing a name from a numeric quantity to a display string halfway through a calculation.
Assuming type hints validate data automatically.
Lesson review
A reliable Python program gives every value a clear meaning, converts text at the boundary, validates before calculation, and preserves the difference between absence and an empty or zero value. Complete the quick checks and knowledge quiz, then rerun the notebook with your own valid and invalid examples.
RUNNABLE PYTHON NOTEBOOK
Build a type-aware order summary
Convert boundary text, validate it, handle an optional coupon, and run several cases—including a failure you can diagnose.
defparse_quantity(raw:str)->int:try:
quantity =int(raw)except ValueError as error:raise ValueError("Quantity must be a whole number")from error
if quantity <1:raise ValueError("Quantity must be at least 1")return quantity
deforder_label(raw_price:str, raw_quantity:str, coupon_code:str|None)->str:
price =float(raw_price)
quantity = parse_quantity(raw_quantity)if price <0:raise ValueError("Price cannot be negative")
discount =0.10if coupon_code =="SAVE10"else0.0
total = price * quantity *(1- discount)
coupon_status = coupon_code if coupon_code isnotNoneelse"no coupon"returnf"{quantity} item(s), {coupon_status}: MAD {total:,.2f}"print(order_label("19.95","3",None))print(order_label("19.95","3","SAVE10"))
OUTPUT
Press Run code to execute this Python program in your browser.
QUICK CHECK
Test what you learned
Which built-in function reports the type of a value?
QUICK CHECK
Test what you learned
Which singleton represents the deliberate absence of a value?
QUICK CHECK
Test what you learned
Which function converts decimal-shaped text such as "19.95" to a number?
KNOWLEDGE QUIZ
Check your values-and-types mental model
Choose an answer for every question, then check the explanations. The goal is not to memorize syntax; it is to predict what Python will do and why.
Values, Variables, and Types Tutorial | SovranCode