Codectionary / Developer documentation / Python

Type Conversion

Python provides built-in functions to explicitly convert values between types - a process often called type casting. int(), float(), str(), and bool() are the most common, letting you turn strings into numbers, numbers into strings, and various values into their boolean equivalent. This is essential whenever data arrives as one type (like text from input()) but needs to be used as another.

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() rounds properly)

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)

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

Handling Invalid Conversions

Converting text that is not actually numeric raises an error, so validate first.

value = "abc"

try:
    number = int(value)
except ValueError:
    print(f"'{value}' is not a valid number")

Best practices

  • Wrap int()/float() conversions of user-provided text in try/except, since invalid text raises a ValueError
  • Remember int() truncates decimals rather than rounding - use round() first if you want proper rounding
  • Know your falsy values: 0, 0.0, "", [], {}, and None are all falsy when converted with bool()
  • Use str() to build messages that combine text and numbers, or use an f-string instead for cleaner syntax

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

True
In Python, True is a built-in constant that represents the boolean value of true. Alongside False, True enables logical and conditional operations. It's a fundamental keyword used throughout Python programming for decision-making, loops, comparisons, and boolean logic. True plays a key role in if statements, while loops, and logical expressions.
False
False is Python's built-in constant representing the boolean value false. It's the logical opposite of True and is essential for conditional logic, loop control, and boolean operations. False is used to indicate negative conditions, failed validations, or when something is not the case. Understanding False is crucial for writing effective control flow in Python programs.
None
None is Python's built-in singleton value that represents the absence of a value or a null result. It is its own type (NoneType) and is commonly used as a default parameter value, a placeholder before a variable is assigned real data, or a function's implicit return value when nothing is explicitly returned. Unlike 0, an empty string, or an empty list, None specifically means 'no value here', not 'an empty value'.
Variables & Assignment
Variables in Python are names bound to values, created the moment you first assign to them - there's no need to declare a type in advance, since Python is dynamically typed. A single variable can be reassigned to a completely different type later in the program. Python also supports several convenient assignment patterns, including assigning multiple variables at once and using augmented assignment operators.