liveBook · Manning

Data conversion

As explained in Python Workout, Second Edition

Type conversion is the transformation of a value from one data type to another, often by calling a target type as a constructor.

Start with a user-input problem: input() always returns a string, so numeric input must be converted before arithmetic or ordering comparisons. Call the target type with the source value, as in int('5') or str(5). section 2.2 section 2.3

Use conversion deliberately when the value's required type changes:

  • Convert guesses with int(input(...)) before comparing them with a randomly generated integer. section 2.3
  • Choose float instead of int when rainfall may contain a floating-point value. section 5.9
  • Construct more complex values by calling their types, such as list('abc') or dict([('a', 1), ('b', 2), ('c', 3)]). section 2.3
  • Remember that + combines strings instead of adding their numeric meanings when conversion is skipped. section 5.9

Convert and validate rainfall input

try: mm_rain = int(input('Enter mm rain: ')) except ValueError: print("You didn't enter a valid integer; try again.") continue rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain This approach lets invalid input return to the loop instead of terminating the program. An alternative checks mm_rain.isdigit() before calling int(), but that rejects negative and floating-point values. section 5.9

try:
    mm_rain = int(input('Enter mm rain: '))
except ValueError:
    print('You didn't enter a valid integer; try again.')
    continue

rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain

Inspect the complete try/except conversion pattern for accepting an integer and accumulating it in a dictionary. section 5.9

How Python Workout, Second Edition covers it

How deep it goes
Explains target-type calls, common mismatches, and two integer-validation strategies, but does not develop conversion internals.
Examples
Demonstrates number guessing, rainfall accumulation, int(), float(), str(), list(), dict(), try/except, and isdigit().
What it assumes
Introduces conversion alongside user input, loops, and comparisons rather than treating those topics as established background.
What you can do after
Apply it via Python type constructors and validation patterns to process numeric user input safely.
How it connects
Connects type conversion with user input, loops, comparison operators, exceptions, strings, integers, floats, lists, and dictionaries.

Also explained in

Compare how 21 books explain data conversion →

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.