Day-2 - Type Casting in Python

In Python, type casting (also known as type conversion) is the process of converting a value from one data type to another.

This is especially useful when working with user input, mathematical operations, or when you need to ensure data is in the right format.


Why Do We Need Type Casting? ๐Ÿค”

Consider this example:

age = input("Enter your age: ")
print(age + 5)   # โŒ Error

Here, input() always returns a string, even if you enter a number. Trying to add a string and an integer will throw an error.

โœ… Solution: Convert the string into an integer using type casting:

age = int(input("Enter your age: "))
print(age + 5)   # Works fine

Types of Type Casting in Python

Python supports two types of conversions:

1. Explicit Type Casting (Manual Conversion)

You manually convert values using built-in functions like int(), float(), str(), bool().

๐Ÿ‘‰ Example:

# String to Integer
print(int("100"))       # 100

# Float to Integer (decimal part removed)
print(int(9.99))        # 9

# Integer to String
print(str(123))         # "123"

# Number to Boolean
print(bool(0))          # False
print(bool(5))          # True

2. Implicit Type Casting (Automatic Conversion)

Sometimes, Python automatically converts data types during operations.

๐Ÿ‘‰ Example:

x = 10       # Integer
y = 2.5      # Float

result = x + y
print(result)        # 12.5
print(type(result))  # <class 'float'>

Here, Python automatically promotes the integer (10) into a float so that both operands are of the same type.


Common Conversion Functions

  1. int() โ†’ Converts values into integers (removes decimals, errors on invalid strings).

  2. float() โ†’ Converts values into floating-point numbers.

  3. str() โ†’ Converts numbers, booleans, or other objects into strings.

  4. bool() โ†’ Converts values into True or False.


Edge Cases โšก

  1. Converting an invalid string to a number โ†’ โŒ Error

     print(int("abc"))  # ValueError
    
  2. Boolean conversion rules:

     print(bool(""))     # False  (empty string)
     print(bool("Hi"))   # True   (non-empty string)
     print(bool(0))      # False
     print(bool(42))     # True
    
  3. Float to int always truncates, not rounds:

     print(int(9.99))   # 9
     print(int(-3.9))   # -3
    

Quick Recap ๐Ÿš€

  • Type Casting = Converting one data type into another.

  • Explicit Casting โ†’ Done using functions (int(), float(), str(), bool()).

  • Implicit Casting โ†’ Done automatically by Python during operations.

  • Be mindful of edge cases (invalid strings, float truncation, boolean rules).


โœจ With type casting, Python gives you complete control over how data behaves in your program โ€” making it flexible, safe, and beginner-friendly!

0
Subscribe to my newsletter

Read articles from Raviteja Vaddamani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raviteja Vaddamani
Raviteja Vaddamani