Guide Python Beginner

5.11 Type Conversion

Implicit type conversion (int promoted to float in mixed arithmetic) vs explicit casting with int(), float(), and str() in Python.

1 min read

Implicit Conversion

What Is It?

Python automatically converts one type to another in certain mixed-type expressions, without you asking — most commonly, int automatically promotes to float when mixed in arithmetic.

Why Is It Used?

It avoids unnecessary manual casting for safe, lossless conversions.

>>> 1 + 2.5    # int automatically promoted to float
3.5
>>> type(1 + 2.5)
<class 'float'>

Explicit Casting Overview

How Is It Used?

For anything not automatic (like str to int), you must call the target type as a function yourself — this was already shown in 5.3 Numeric Data Types, repeated here as the general pattern:

>>> int("10") + 5
15
>>> str(15) + " items"
'15 items'

Quick Interview Answer

“Implicit conversion happens automatically in mixed-type expressions — int promotes to float in arithmetic like 1 + 2.5. Explicit conversion (casting) is anything Python won’t do on its own, like str to int — you call the target type as a function yourself: int(\"10\"), float(\"3.14\"), str(42).”

Common Mistakes

  • Expecting Python to implicitly convert a str to a number in arithmetic — it doesn’t; "10" + 5 raises a TypeError, unlike some other dynamically typed languages.
  • Forgetting that int("3.14") raises a ValueError — going from a decimal string to int requires int(float("3.14")), an explicit two-step conversion.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form