Python Tutorials | Type Conversion in Python

In Python, variables can hold data of different types such as integers, strings, floats, and Booleans. Sometimes, it's necessary to convert one data type into another — a process known as type conversion or type casting.

Python makes type conversion easy using built-in functions like int(), str(), float(), and bool(). Let’s explore how these work with hands-on examples.

Example 1: Converting String to Integer

num_str = "100"
num_int = int(num_str)
print(num_int + 50)

Here, a string containing a number is converted into an integer using int().

Example 2: Converting Integer to String

age = 30
message = "You are " + str(age) + " years old."
print(message)

You can’t concatenate an integer with a string directly. Use str() to convert the integer into a string first.

Example 3: Converting String to Float

price_str = "49.99"
price = float(price_str)
print(price * 2)

float() is used to convert a numeric string with a decimal into a float type.

Example 4: Converting Float to Integer

value = 9.8
new_value = int(value)
print(new_value)

Converting a float to an integer using int() will remove the decimal part (not round).

Example 5: Converting Boolean to Integer

print(int(True))   # Output: 1
print(int(False))  # Output: 0

Booleans can be converted to integers. True becomes 1, and False becomes 0.

Example 6: Converting Integer to Boolean

print(bool(10))   # True
print(bool(0))    # False

Any non-zero number converts to True; zero converts to False.

Example 7: Converting String to Boolean

print(bool("Hello"))  # True
print(bool(""))       # False

A non-empty string becomes True, while an empty string becomes False.

Example 8: Implicit Type Conversion

x = 5
y = 3.0
result = x + y
print(result)
print(type(result))

In expressions, Python automatically converts the result to a more precise type (integer + float becomes float).

Example 9: Using str() with Different Types

print(str(3.14))     # "3.14"
print(str(True))     # "True"
print(str(None))     # "None"

The str() function works with any object and converts it into its string representation.

Example 10: Converting Input for Calculation

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
total = int(num1) + int(num2)
print("Total:", total)

User inputs are always strings by default. You must convert them before performing numeric operations.


Summary

  • int() converts values to integers
  • float() converts to decimal numbers
  • str() converts any value to a string
  • bool() checks truthy or falsy values
  • Python also performs implicit conversion in expressions

Type conversion is essential when working with user input, mathematical calculations, and data processing. Mastering these functions allows you to write more flexible and reliable Python programs.