Tutorials Logic, IN info@tutorialslogic.com

Type Conversion in Python Implicit Explicit

Conversion Basics

Type conversion changes a value from one type to another, such as text from input() into an integer before doing math.

Some conversions happen automatically, but important beginner code should convert explicitly so the intent is visible.

Good conversion code also handles invalid values, because real user input does not always match the type your program expects.

Type Conversion

Type conversion (also called type casting) is the process of converting a value from one data type to another. Python supports two kinds: implicit and explicit.

Implicit Type Conversion

Python automatically converts types when it's safe to do so - no data is lost. This usually happens when mixing int and float.

Implicit Conversion

Implicit Conversion
x = 5       # int
y = 2.5     # float

result = x + y
print(result)        # 7.5
print(type(result))  # <class 'float'>  - Python promoted int to float

# bool is a subclass of int
print(True + 1)   # 2
print(False + 5)  # 5
print(True * 10)  # 10

Explicit Conversion

You manually convert using built-in functions. This is called explicit conversion or type casting.

Function Converts To Example
int(x) Integer int("42") -> 42
float(x) Float float("3.14") -> 3.14
str(x) String str(100) -> "100"
bool(x) Boolean bool(0) -> False
list(x) List list("abc") -> ['a','b','c']
tuple(x) Tuple tuple([1,2,3]) -> (1,2,3)
set(x) Set set([1,2,2,3]) -> {1,2,3}
dict(x) Dictionary dict(a=1, b=2)
complex(r, i) Complex complex(2, 3) -> (2+3j)
ord(c) Integer (Unicode) ord('A') -> 65
chr(n) Character chr(65) -> 'A'
hex(n) Hex string hex(255) -> '0xff'
oct(n) Octal string oct(8) -> '0o10'
bin(n) Binary string bin(10) -> '0b1010'

Explicit Conversion Examples

Explicit Conversion Examples
# Numeric conversions
print(int(3.9))
print(int("42"))
print(int("0b1010", 2))
print(float("3.14"))

# Falsy and truthy values
print(bool(0))
print(bool(""))
print(bool([]))
print(bool(None))
print(bool(1))
print(bool("hi"))

# Collection conversions
print(list("Python"))
print(tuple([1, 2, 3]))
print(set([1, 2, 2, 3, 3]))

print(ord("A"))
print(chr(65))

Conversion Mistakes

Pitfalls & Error Handling

Pitfalls & Error Handling
# int() truncates, doesn't round
print(int(9.9))   # 9 (not 10!)
print(int(-3.7))  # -3 (not -4!)

# Use round() if you need rounding
print(round(9.9))   # 10
print(round(3.567, 2))  # 3.57

# ValueError - invalid conversion
try:
    x = int("hello")
except ValueError as e:
    print(f"Error: {e}")  # invalid literal for int()

# Safe conversion pattern
def safe_int(value, default=0):
    try:
        return int(value)
    except (ValueError, TypeError):
        return default

print(safe_int("42"))      # 42
print(safe_int("abc"))     # 0
print(safe_int(None))      # 0

# User input is always a string - always convert!
age_str = input("Enter age: ")  # returns str
age = int(age_str)              # convert to int
Conversion checkpoint

Can You Convert Values Safely?

5 checks
  • Type conversion (also called type casting) is the process of converting a value from one data type to another.
  • Python supports two kinds: implicit and explicit.
  • Python automatically converts types when it's safe to do so - no data is lost.
  • This usually happens when mixing int and float.
  • You manually convert using built-in functions.

Conversion Decisions

0 of 2 checked

Q1. What should happen before adding two numbers read from input()?

Q2. Which error is likely from int("abc")?

Conversion Failures to Handle

  • Converting input too late

    Convert text from input() before doing numeric calculations.
  • Assuming every string can become a number

    Validate or catch ValueError when user text may be empty or non-numeric.
  • Losing decimal values with int()

    Use float() or Decimal when the fractional part matters.

Try this next

Convert Real Input

0 of 3 completed

  1. Ask for quantity and price, convert both, and print the total.
  2. Try converting abc to int and explain the ValueError message.
  3. Decide whether age, temperature, price, and item count should use int or float.

Questions About Conversion

input() returns text. If the program needs math, convert the text with int() or float() after checking that the value is valid.

Python raises ValueError, such as int("abc"). Handle it with validation or a focused try except block.

No. Convert at the boundary where data enters the program, then keep the value in the type the program needs.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.