Course outline

Python / Foundations / Lesson 2

Values, types, and expressions

Choose representations that preserve meaning, perform deliberate conversions, and reason about arithmetic and truth without confusing text with numbers.

About 4 min readContent reviewed
On this page

Lesson goals

  • Objects have types
  • Truth and comparisons

Objects have types

A Python value is an object with a type that determines its available operations. Integers represent whole numbers, floats approximate real quantities, strings represent Unicode text, and Booleans express truth. None marks absence when absence is part of the contract. A name can later refer to another type, but the current object still has definite behavior. Ask what a value represents before choosing its type: a postal code is text even when all its characters are digits, because leading zeros and identity matter more than arithmetic. Clear representations prevent errors before any conditional validation becomes necessary.

Arithmetic and precedence

Expressions combine values through operators. Multiplication binds more tightly than addition; parentheses document an intended grouping when a reader might hesitate. Division with / produces a float, while // computes a floor quotient and % gives a corresponding remainder. Floor means toward negative infinity, so negative operands deserve explicit examples rather than assumptions from truncation in another language. Exponentiation uses ** rather than ^, which is bitwise exclusive-or for integers. Keep units in names or documentation: adding minutes to hours without conversion is a modeling error even when the interpreter happily computes a number.

Convert at boundaries

External text does not automatically become numeric data. int("12") explicitly parses an integer representation, whereas str(12) produces text for display. The input function also returns text; the runnable example uses a fixed string so no interactive entry is required. Conversion can fail, which later lessons handle with targeted exceptions. Keep the original text when it is useful for reporting a bad field, then pass validated numeric values into calculations. Formatting the final result is a separate boundary. Mixing those stages tends to create repeated conversions and makes it harder to identify which operation actually failed.

python Convert at boundaries — worked example
text = "12"
count = int(text)
print(count * 3)
print(17 // 5, 17 % 5)
Expected output
36
3 2

The parser yields an integer before multiplication. Quotient and remainder reconstruct seventeen as three groups of five plus two.

Approximation and exactness

Binary floating-point represents many decimal fractions approximately. A surprising printed result does not imply that Python randomly changed the calculation. For measured quantities, compare with an appropriate tolerance, using math.isclose when its relative and absolute tolerances suit the domain. For exact decimal arithmetic such as a deliberately decimal price model, Decimal constructed from strings preserves decimal inputs. Constructing it from a float imports the float’s approximation. Neither choice supplies rounding policy automatically: the application must define units, precision, rounding points, and acceptable differences. The example deliberately contrasts representation behavior rather than recommending one type for every calculation.

python Approximation and exactness — worked example
from decimal import Decimal
from math import isclose

print(0.1 + 0.2 == 0.3)
print(isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"))
Expected output
False
True
0.3

Exact float equality fails for this calculation, the tolerance comparison succeeds, and string-based Decimal arithmetic gives the exact decimal sum.

Truth and comparisons

Comparisons such as < and == produce Boolean results. Use == for value equality and is primarily for identity checks such as value is None. Empty containers, numeric zero, None, and False are false in a condition, but the nonempty string "False" is true because it contains text. Converting that string with bool does not parse a user’s yes-or-no answer. Define accepted words explicitly when implementing such a parser. Python also supports chained comparisons such as 0 <= score <= 100, which clearly expresses a range without an accidental logical gap between two separately maintained checks.

Common errors and fixes

TypeError while adding text and an integer

Why it happens
The operands represent different operations and no parsing was requested.
How to fix it
Parse numeric text before arithmetic or format both values as text.
Prevent it next time
Separate input parsing, domain calculation, and output formatting.

A decimal equality check unexpectedly fails

Why it happens
Binary floats approximate the chosen decimal fractions.
How to fix it
Use an explicit tolerance or a deliberate exact representation.
Prevent it next time
Document precision and rounding rules with realistic boundary cases.

bool("False") returns True

Why it happens
Any nonempty string is truthy regardless of its spelling.
How to fix it
Compare normalized input against explicit accepted tokens.
Prevent it next time
Test empty, accepted, rejected, and differently cased input.

Check your understanding

1. Convert 137 minutes into whole hours and remaining minutes.

Show worked solution

Compute hours = 137 // 60 and minutes = 137 % 60. The result is 2 hours and 17 minutes. Verify 2 * 60 + 17 == 137 and 0 <= 17 < 60; these checks capture both reconstruction and the remainder’s valid range.

2. Explain why a product code "0042" should often remain a string.

Show worked solution

The code identifies an item rather than measuring a quantity. int("0042") yields 42 and discards meaningful leading zeros. Store the code as text, compare its normalized spelling under a documented policy, and convert only a separate quantity field to an integer.

Key takeaways

  • Representation should follow meaning and units.
  • Conversion and rounding are explicit design decisions.
  • Truthiness is different from parsing Boolean text.

Official references