liveBook · Manning

Floating-point arithmetic

As explained in Python Workout, Second Edition

float is Python's built-in constructor and conversion function for creating floating-point number objects.

Floating-point arithmetic represents numbers with fractional components. Python provides float as both a numeric type and a constructor for converting values such as strings and integers into floating-point objects. section 2.0 section 2.18

Use floating-point values when a calculation requires fractional quantities, while watching for these practical concerns:

  • Convert user input before arithmetic: input returns a string, so adding unconverted values concatenates strings instead of adding numbers. section 5.9
  • Track both accumulated values and their count when calculating an average, and preserve floating-point inputs and outputs where required. section 2.10
  • Treat floats as potentially inexact; explore Decimal when decimal input such as 0.1 and 0.2 must produce an accurate decimal sum. section 2.13

Average repeated run times

A run_timing function repeatedly asks for 10-kilometer run times until Enter is pressed, converts each response to a float, accumulates the values, counts the runs, and displays their average. Three entries—15, 20, and 10—produce an average of 15.0 over three runs. section 2.10

Enter 10 km run time: 15
Enter 10 km run time: 20
Enter 10 km run time: 10
Enter 10 km run time: <enter>

Average of 15.0, over 3 runs

The sample interaction shows repeated floating-point input, termination with Enter, and an explicitly floating-point average. section 2.10

How Python Workout, Second Edition covers it

How deep it goes
Explains types, conversions, accumulation, and inexact representation, then defers exact decimal behavior to Decimal.
Examples
Uses running-time averages, fractional slicing, Decimal sums, and rainfall values entered through input.
What it assumes
Assumes basic Python numeric and input handling while reinforcing distinctions among strings, integers, and floating-point values.
What you can do after
Apply it via Python's float constructor to convert numeric input, accumulate fractional values, and calculate averages.
How it connects
Connects float with int, complex numbers, strings, input, averages, dictionaries, and Decimal.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.