liveBook · Manning

Data conversion

As explained in Get Programming: Learn to code with Python

Data conversion is the transformation of a value or data from one type, format, or representation to another, explicitly or implicitly.

Data conversion gives a value a different type so you can use it in a new way. In Python, put the value inside the name of the type you want: int(...), float(...), or str(...). Use type(...) in the console when you want to check a value’s type. section 5.3

Try these small conversions:

  • float(4) gives 4.0; int("4") gives the number 4 rather than the string "4". section 5.3
  • str(3.5) gives "3.5". int(3.94) gives 3: the part after the decimal point is removed. section 5.3
  • int(False) gives 0 and int(True) gives 1. But int("a") causes an error because "a" is not a number. section 5.3

Turn typed input into a number

user_input = input("Enter a number: ") num = int(user_input) print(num * num) First, input() waits for an answer and returns a string, even if the user types digits. Next, int(...) converts that string to a number. Only then does the program multiply it. If the answer is not a numeric string, the conversion fails. section 11.2 section 5.3

Make an index from a division result

halfway = int(len(name) / 2) first_half = name[0:halfway] Dividing an odd name length by 2 produces a decimal value, which cannot serve as a string index. Converting it with int(...) gives a whole-number halfway point; for a five-letter name, the first slice has two letters. section 12.3

Keep type conversion separate from changing what a number measures. For example, a minutes-to-hours program divides by 60 to change units, then uses int(...) to turn the decimal hours result into a whole-number hours value. Quick check: what do int(0.5) and str(True) produce? section 6.3 section 5.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines explicit conversions and works through results, truncation, and an invalid string; does not explain implementation internals.
Examples
Uses short int, float, and str expressions, a squared user input, whole hours from minutes, and name halves.
What it assumes
Introduces values, types, and expressions before conversion; later slicing examples assume familiarity with strings and indices.
What you can do after
Practice/perform it by converting typed numbers for calculations and division results into usable whole-number indices.
How it connects
Connects data types with user input, arithmetic, string slicing, and printing.

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 Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.