Python Casting


Casting in Python refers to converting one data type to another manually using built-in functions.

Although Python is dynamically typed (automatically detects data types), sometimes you need to explicitly convert values from one type to another.


🔄 Types of Type Casting in Python

Python provides the following built-in functions for casting:

Function Purpose
int() Converts to integer
float() Converts to float
str() Converts to string
bool() Converts to boolean

🧮 1. Convert to Integer — int()

Used to convert a number or a numeric string to an integer.

x = int(5.6)        # Result: 5
y = int("10")       # Result: 10

❗ Cannot convert non-numeric strings:

int("abc")  # Error

🔢 2. Convert to Float — float()

Converts integer or numeric string to float.

a = float(7)        # Result: 7.0
b = float("3.14")   # Result: 3.14

🔤 3. Convert to String — str()

Converts numbers or other data types to string.

x = str(100)        # Result: "100"
y = str(3.14)       # Result: "3.14"

✅ 4. Convert to Boolean — bool()
  • bool(0), bool(""), bool(None) return False

  • All other values return True

bool(1)      # True
bool(0)      # False
bool("Hi")   # True

🧠 Why Use Casting?

  • To perform operations between different types

  • To store data in a specific format

  • To avoid type errors in calculations or concatenation


✅ Summary Table

From To Method Example Result
float int int(5.6) 5
int float float(2) 2.0
number string str(100) "100"
string int int("25") 25
any boolean bool(value) True / False

Practice Questions

Q1. Write a Python program to convert the float 3.7 to an integer using int().

Q2. Write a Python program to convert the string "25" to an integer using int().

Q3. Write a Python program to convert the number 100 to a string and print its type.

Q4. Write a Python program to convert the integer 50 to a float using float().

Q5. Write a Python program to try converting the string "abc" to an integer and observe the error.

Q6. Write a Python program to convert an empty string "" to boolean and display the result.

Q7. Write a Python program to use str() to convert a boolean value to a string and print it.

Q8. Write a Python program to convert the string "7.5" to a float using float().

Q9. Write a Python program to convert a non-zero number like 10 to boolean and print the result.

Q10. Write a Python program to convert a float value 5.99 to a string using str() and check its type.


Go Back Top