Python Variable & Data Type

Type Casting in Python

Learn Type Casting in Python with clear explanations, Python examples, and practical programming guidance.

What is type casting in Python?

Type casting, also called type conversion, is the process of converting a value from one data type to another. It is useful when data comes from different sources or when an operation requires a particular type.

Python is dynamically typed, so you do not declare a variable's type before assigning a value. Python still checks the types of objects at runtime, and incompatible operations can raise an error.

Implicit and explicit conversion

KindWho performs it?Example
Implicit conversionPython performs it automatically when the conversion is safe.5 + 2.5 produces a float.
Explicit conversionThe programmer calls a conversion function.int("42") produces an int.

Implicit type conversion

Python can promote an integer to a float or complex number during an expression. This helps prevent accidental loss of information:

integer_value = 5
float_value = 7.6
complex_value = 3 + 4j

float_result = integer_value + float_value
complex_result = integer_value + float_value + complex_value

print(float_result, type(float_result))
print(complex_result, type(complex_result))
12.6 <class 'float'>
(15.6+4j) <class 'complex'>

Python does not automatically convert a float to an integer because that could discard the fractional part. It also does not implicitly convert arbitrary text to a number.

Common explicit conversion functions

FunctionPurposeExample
int()Converts a compatible value to an integer.int("14")14
float()Converts a compatible value to a floating-point number.float("21.73")21.73
complex()Creates a complex number from a real value or real and imaginary parts.complex(8)8+0j
str()Converts a value to its text representation.str(25)"25"
bool()Converts a value to True or False.bool(1)True
list(), tuple(), set()Converts an iterable to a collection type.list("cat")["c", "a", "t"]
dict()Builds a dictionary from key-value pairs or a mapping.dict([("language", "Python")])

Converting values to integers

The int() function converts compatible integers, numeric strings, and floating-point values. When converting a float, it truncates the fractional part toward zero:

from_float = int(16.8)
from_text = int("14")

print(from_float)
print(from_text)
print(type(from_text))
16
14
<class 'int'>

Use round() when rounding is required. For example, round(16.8) returns 17; int(16.8) returns 16.

Converting values to floats

Use float() to convert an integer or a numeric string to a floating-point value:

from_integer = float(19)
from_text = float("21.73")

print(from_integer)
print(from_text)
print(type(from_text))
19.0
21.73
<class 'float'>

Converting values to complex numbers

The complex() function can convert a real value to a complex number or accept separate real and imaginary parts:

first = complex(5)
second = complex(8.9)
third = complex(3, 4)

print(first)
print(second)
print(third)
(5+0j)
(8.9+0j)
(3+4j)

Converting values to strings

The str() function creates a text representation of a value. This is useful when building messages or combining converted values with text:

age = 25
message = "Age: " + str(age)

print(message)
print(type(message))
Age: 25
<class 'str'>

In modern Python, an f-string is often clearer when inserting values into text:

name = "Asha"
age = 25
print(f"{name} is {age} years old")

Boolean conversion and truthy values

bool() returns False for values such as 0, 0.0, an empty string, an empty collection, and None. Most other values are truthy:

print(bool(0))
print(bool(""))
print(bool("Python"))
print(bool([]))
print(bool([1, 2]))
False
False
True
False
True

This behavior is why collections can be used directly in conditions such as if items:.

Converting collections

Collection conversion functions consume an iterable. A string becomes a sequence of characters, and a set removes duplicate values:

letters = list("cat")
coordinates = tuple([10, 20])
unique_values = set([1, 1, 2, 3])
mapping = dict([("language", "Python")])

print(letters)
print(coordinates)
print(unique_values)
print(mapping)

Be aware that sets are unordered and remove duplicates. A dictionary conversion requires data that can be interpreted as key-value pairs.

Converting user input

input() always returns a string, even when the user enters digits. Convert the value before using it in a numeric calculation:

age_text = input("Enter your age: ")
age = int(age_text)
print(age + 1)

Real applications should handle invalid input with try and except:

try:
    age = int(input("Enter your age: "))
    print(age + 1)
except ValueError:
    print("Please enter a whole number.")

Common type-casting errors

  • int("3.5") raises ValueError; convert to float first if decimal text is expected.
  • int("Python") cannot convert arbitrary text to a number.
  • int(4.9) truncates to 4; it does not round.
  • Converting a value to bool checks whether it is empty or zero, not whether its text says “true”.
  • Some conversions lose information, so keep the original value when precision matters.

Best practices

  • Convert values at the boundary of your program, such as immediately after reading user input.
  • Validate external data and handle ValueError when conversion can fail.
  • Use Decimal for exact decimal calculations instead of relying on binary floats.
  • Choose conversion functions intentionally and document conversions that may lose precision.

Further Reading

Continue learning with these related Python tutorials:

Continue learning