Codectionary / Developer documentation / Python

Type Conversion

Conversion creates a value of a requested type when the input has a suitable representation. int(), float(), str() and bool() are common built-ins. Use explicit conversion at input boundaries rather than hoping Python will add text and numbers together.

How it works

int("25") parses integer text, while float("19.99") parses floating-point text. int("3.5") fails because that text is not an integer representation. int(3.5) accepts a numeric float and truncates it towards zero. Converting through float first can lose precision and is not a general-purpose integer validation strategy.

bool() tests truthiness, not the spelling of text: bool("False") is True because the string is nonempty. To parse a yes/no setting, compare against an explicit set of accepted strings and reject unknown values.

str() produces a display representation. Converting a list to str does not produce a reliable data interchange format; use a format such as JSON when another program needs to read the result.

Common mistakes and boundaries

Catch ValueError for malformed numeric text. An unsuitable object type can raise TypeError instead. Catch the specific errors your input contract allows.

int() truncates; round() follows rounding rules rather than simply discarding digits. For built-in numbers, round() uses ties-to-even when values are equally close, and binary float representation can affect apparent decimal ties.

Try it yourself

Try int("-7"), int(-7.9), int("7.9") and bool("False"). Predict both values and failures before running them. Write a yes/no parser that accepts only the words you intend.

Syntax

int(x)  float(x)  str(x)  bool(x)

Examples

Numeric Conversions

Converting between integers and floats.

whole = int(9.8)     # 9  (truncates, doesn't round)
decimal = float(5)   # 5.0

print(whole, decimal)
print(round(9.8))    # 10 (round() chooses the nearest integer here)
  1. int drops the fractional part towards zero, while float creates a floating-point value. round(9.8) selects the nearest integer here.
  2. Expected output: 9 5.0 10

Converting To and From Strings

A very common conversion when handling user input or building output.

age = int("25")
price = float("19.99")
print(age + 1, price * 2)

score = 95
message = "Your score is " + str(score)
print(message)
  1. Parsing creates numeric values for arithmetic; str converts the score for concatenation.
  2. Expected output: 26 39.98 Your score is 95

Converting to Boolean

Understanding which values are considered "truthy" and "falsy" when converted with bool().

print(bool(0))       # False
print(bool(1))       # True
print(bool(""))      # False - empty string
print(bool("hi"))    # True - non-empty string
print(bool([]))      # False - empty list
print(bool([1, 2]))  # True - non-empty list
print(bool(None))    # False
  1. Zero, empty containers and None are falsy; nonzero numbers and nonempty containers are truthy.
  2. Expected output: False True False True False True False

Handling Invalid Conversions

Attempt conversion and handle invalid numeric text with a specific exception.

value = "abc"

try:
    number = int(value)
except ValueError:
    print(f"'{value}' is not a valid number")
  1. The conversion is attempted inside try. The except block handles this specific malformed string without terminating the program.
  2. Expected output: 'abc' is not a valid number

Best practices

  • Parse input explicitly and handle expected conversion errors.
  • Distinguish truncation from rounding and choose the operation your problem needs.
  • Do not parse Boolean words with bool(text); nonempty text is truthy.
  • Prefer f-strings for readable display messages and a serialisation format for stored data.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading