Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Converting Data Types

In Python, we can convert (or cast) one data type to another using built-in functions. This is useful when working with user inputs, arithmetic operations, and more.


1. Converting Between Types

Converting to Integer (int())

You can convert a string or float to an integer.

num_str = "100"
num_float = 45.8

num1 = int(num_str)   # Converts string to int
num2 = int(num_float) # Converts float to int (removes decimal)

print(num1)  # Output: 100
print(num2)  # Output: 45

? Note: Converting a float to an integer truncates (removes) the decimal part, it does not round the number.


Converting to Float (float())

Convert integers and strings to floats.

num_int = 20
num_str = "99.5"

num1 = float(num_int)  # Converts integer to float
num2 = float(num_str)  # Converts string to float

print(num1)  # Output: 20.0
print(num2)  # Output: 99.5

Converting to String (str())

Convert numbers to strings.

age = 25
price = 10.99

str_age = str(age)
str_price = str(price)

print(str_age)   # Output: '25'
print(str_price) # Output: '10.99'

This is useful when concatenating numbers with text:

print("I am " + str(age) + " years old.")  
# Output: I am 25 years old.

Converting to Boolean (bool())

Python considers these values False when converted to boolean:

  • 0
  • 0.0
  • '' (empty string)
  • None

All other values are True.

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

2. Type Conversion Errors

Not all conversions are possible!

num = int("Hello")  #  Error! Can't convert text to a number.

Always check or handle errors when converting data types.


Exercise: Try It Yourself!

  1. Convert "123" to an integer and add 10 to it.
  2. Convert 3.14 to an integer. What happens?
  3. Convert 0, "", and "Python" to boolean. What are the results?