liveBook · Manning

Floating-point arithmetic

As explained in The Quick Python Book, Fourth Edition

A floating-point number is a numeric value represented using a finite-precision floating-point format.

A Python float represents a number with a fractional part or a value written in scientific notation, such as 3.14 or 2.0e-8. Its precision depends on the underlying machine and is typically comparable to a C double. Unlike Python integers, floats do not have an unlimited range of precision. section 4.7

The operators and conversions most likely to matter are:

  • Division with / returns a float even when both operands are integers: 5 / 2 gives 2.5. Use // when integer operands should produce a whole-number result: 5 // 2 gives 2. section 4.7
  • An operation involving a float produces a float: 30000000000 * 3.0 gives 90000000000.0. float(200) gives 200.0; int(200.2) discards the fractional part and gives 200. section 4.7
  • float('123.456') converts a numeric string. A string that cannot be interpreted as a number raises ValueError. section 6.4.2

Calculate an average

x = 3 y = 5 z = (x + y) / 2 z is 4.0. The parentheses make the addition happen before division; without them, the expression would be x + (y / 2). section 4.5

input() returns a string, so convert it with float() before using it as a float. When invalid input is possible, catch ValueError: a spreadsheet cell converter can return 0 for an empty cell and None for other nonnumeric text. section 4.9 section 14.2.9

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains literals, operator results, conversions, and typical machine precision without detailing floating-point representation internals.
Examples
Compares 5 / 2 with 5 // 2, converts 200.2 and numeric strings, and calculates an average.
What it assumes
Assumes familiarity with standard numeric operations while teaching Python-specific division and conversion behavior.
What you can do after
Apply float() to convert numeric strings, use / for fractional division, and handle invalid conversions with ValueError.
How it connects
Connects floats to integers, arithmetic operators, string conversion, user input, and ValueError handling.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.