Yandex

Python Type Conversions



What are Type Conversions in Python?

In Python, data can exist in different forms — like strings, integers, floats, or booleans. Sometimes, you may need to convert one type into another. This process is called type conversion or type casting.

Why Do We Need Type Conversion?

Imagine asking Python to add a number and a string — it won’t make sense unless both are of the same type. Type conversion allows us to:

  • Handle user input correctly (which is always a string)
  • Perform mathematical operations
  • Clean and process data
  • Work with files, databases, or external APIs

Types of Type Conversion

Python supports two main types of conversions:

  1. Implicit Type Conversion – automatically handled by Python
  2. Explicit Type Conversion – done manually by the programmer

Implicit Type Conversion

Python automatically promotes compatible data types during operations. For example, it promotes an int to a float when needed.

x = 5
y = 2.0
result = x + y
print(result)
print(type(result))
7.0
<class 'float'>

Explicit Type Conversion

This is where you take control using Python’s built-in conversion functions. Let’s explore them one by one.

Convert String to Integer

s = "123"
num = int(s)
print(num)
print(type(num))
123
<class 'int'>

What If the String Is Not a Number?

Be careful — if the string is not a valid integer, Python throws a ValueError.

s = "abc"
num = int(s)  # This will crash
ValueError: invalid literal for int() with base 10: 'abc'

Convert String to Float

s = "12.34"
f = float(s)
print(f)
print(type(f))
12.34
<class 'float'>

Convert String to Boolean

In Python, any non-empty string is considered True. An empty string is False.

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

Convert Number to String

Converting a number to string is often needed while building messages, filenames, or storing data.

age = 25
text = "I am " + str(age) + " years old"
print(text)
I am 25 years old

Convert Float to Integer

When you convert a float to an int, it chops off everything after the decimal point. It doesn’t round — it truncates.

value = 3.99
print(int(value))
3

Using type() to Verify

Always verify what type you are working with using type(). It helps avoid confusion and bugs.

x = "123"
print(type(x))       # Before conversion
x = int(x)
print(type(x))       # After conversion
<class 'str'>
<class 'int'>

Common Conversion Functions

FunctionDescription
int()Converts to integer
float()Converts to float
str()Converts to string
bool()Converts to boolean

Best Practices and Gotchas

  • Validate your string data before converting to numbers.
  • Use try-except blocks to handle conversion errors.
  • Don’t assume an empty string is None — it’s False in a boolean context, but still a valid string.

Quick Summary

  • Type conversion is converting between different data types like string, int, float, and bool.
  • Implicit conversion is done automatically.
  • Explicit conversion is done using functions like int(), str(), etc.
  • Always validate strings before converting to int or float.

Practice Time

Try converting these values and guess the results before running:

print(int("5.5"))       # Will it work?
print(bool("False"))    # What does this return?
print(float("123abc"))  # Valid or not?

Once you get comfortable with these conversions, Python starts to feel more like a friendly assistant than a strict gatekeeper.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M