PYTHON / CHAPTER 06

Values, text, and arithmetic

Beginner

Choose operations that match the meaning of the data.

By the end of this chapter

  • Trace integer division and remainder
  • Read slices with exclusive stops
  • Use explicit conversion and formatted strings

The idea

Python names refer to objects, and the object determines which operations are available. Text and numbers are different kinds of data: convert deliberately instead of expecting arithmetic to interpret a string. For nonnegative whole quantities, floor division and remainder split a total into larger units and a leftover. Ordinary division produces a floating-point result even when both inputs are integers.

Strings are immutable sequences. Indexing selects a character, while a slice selects a range whose stop is excluded. A slice does not change the original string. Negative indices count from the end, and omitted slice bounds use the relevant edge. Use formatted strings to construct readable output, keeping calculation separate from presentation so each part can be tested independently.

Python example
seconds = 125
minutes, remaining = divmod(seconds, 60)
print(f"{minutes}:{remaining:02d}")
print("ticket"[1:4])
Result
2:05
ick

divmod returns the quotient and remainder together. The slice includes indices one, two, and three, stopping before index four.

Try it yourself

Format a nonnegative duration in hours, minutes, and seconds without wrapping hours at 24.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open Python coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What value is produced by "report"[1:4]?