Type conversion (also called casting) is the process of changing a value from one data type to another. A number stored as a string cannot be used in a calculation until converted; a number cannot be joined to a string until converted to text. Getting data types right is one of the most common programming challenges.

What is a data type and why does it matter?

Every value in a program has a data type — a classification that tells the computer what kind of data it is and what operations are valid on it.

Data type What it stores Example In Python
Integer Whole numbers 42, –7, 0 int
Float Decimal numbers 3.14, –0.5 float
String Text (sequence of characters) "hello", "42" str
Boolean True or False True, False bool

The key insight: 42 (an integer) and "42" (a string of two characters) look identical to a human but are completely different to the computer. You can add 42 + 8 = 50, but "42" + "8" produces "428" — string concatenation joins them together, it does not add them.

What is the difference between implicit and explicit conversion?

Implicit conversion (also called coercion) happens automatically when Python decides it is safe to change a type. For example, when you add an integer and a float, Python automatically converts the integer to a float:

result = 5 + 2.0    # Python converts 5 to 5.0
print(result)        # outputs 5.0 (a float)

Explicit conversion (casting) is when the programmer deliberately calls a function to convert a value:

age_string = "15"
age = int(age_string)   # programmer explicitly converts
next_year = age + 1     # now works: 16

Python is reluctant to guess when a conversion might lose information or produce a wrong result, so it generally requires explicit casting in those cases.

How do you convert types in Python?

Python provides built-in functions for the most common conversions:

Function Converts to Example Result
int(x) Integer int("42") 42
int(x) Integer (from float) int(3.9) 3 (truncates, not rounds)
float(x) Float float("3.14") 3.14
str(x) String str(99) "99"
bool(x) Boolean bool(0) False

Critical detail about int() on floats: int() truncates toward zero — it removes the decimal part without rounding. int(3.9) gives 3, not 4. int(–3.9) gives –3, not –4. If you need rounding, use round() first.

What happens when a conversion fails?

Not every conversion is possible. Calling int("hello") does not make sense — "hello" has no numerical value. Python raises a ValueError and the program crashes:

value = int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'

This is why input validation is important. When accepting user input (which always arrives as a string), you should check the input is suitable before converting it. A common pattern:

user_input = input("Enter your age: ")
if user_input.isdigit():
    age = int(user_input)
else:
    print("Please enter a whole number.")

Worked example: a calculator that reads user input

When a user types a number in response to input(), Python always stores it as a string. If you try to add two inputs without converting them, you get concatenation instead of addition:

# Bug — strings concatenate instead of adding
a = input("Enter first number: ")   # user types 5
b = input("Enter second number: ")  # user types 3
print(a + b)                         # outputs "53", not 8

Corrected version:

a = int(input("Enter first number: "))   # convert immediately
b = int(input("Enter second number: "))
print(a + b)                              # outputs 8

Best practice: convert inputs at the point of entry so the rest of the program works with the correct types from the start.

Why do programs need type conversion?

Type conversion arises whenever data crosses a boundary:

  • User input: input() always returns a string — must be cast before arithmetic.
  • File reading: data read from a text file arrives as strings — must be cast to numbers for calculations.
  • Output formatting: combining numbers and text requires converting numbers to strings first: "Score: " + str(score).
  • Databases: data fetched from a database may need casting to the expected type.

Frequently asked questions

Why does Python not just convert types automatically all the time?

Automatic conversion would often produce the wrong result silently. If Python automatically converted "42" to 42 in all arithmetic, the concatenation "4" + "2" could never produce "42". If it auto-converted in all string contexts, you could never get "42" from the integer 42 using +. By keeping types strict and requiring explicit conversion, Python forces you to declare your intent — this prevents a large class of subtle bugs where the wrong conversion happened silently.

What is the difference between int() and round()?

int() truncates the decimal part — it always moves toward zero. round() rounds to the nearest integer (with ties going to the nearest even number, per Python's "banker's rounding"). Use int() when you want to discard the fractional part deliberately (e.g. converting a float index to a usable array position). Use round() when you want the mathematically nearest whole number (e.g. rounding a price to the nearest pound).

Can you convert a Boolean to an integer in Python?

Yes. In Python, True converts to 1 and False converts to 0: int(True) returns 1. Conversely, bool(0) returns False and bool(1) (or any non-zero number) returns True. This is occasionally useful in counting problems: sum([True, False, True, True]) returns 3 — the count of True values. However, relying on this conversion makes code harder to read, so use it only when its meaning is clear.

What does str() do to a float like 3.0000000001?

Python's str() converts the float exactly as Python represents it internally, which can produce surprising strings for certain floating-point values. str(3.1 + 0.0) gives "3.1", but floating-point arithmetic is imprecise and values such as 0.1 + 0.2 give 0.30000000000000004. For displaying monetary values or controlled decimal places, use an f-string: f"{value:.2f}" formats to exactly two decimal places, regardless of the internal float representation.


Professor Turing can walk you through type conversion, data types, and all KS3 programming fundamentals — one question at a time — at aitutors.me.