Type Conversion in Python (Casting Between Types)

Type conversion in Python means changing a value from one type to another.

This is very common when working with:

  • user input
  • file data
  • numbers stored as text
  • text messages that include numbers

Python gives you built-in functions like int(), float(), str(), and bool() to do this. Beginners often call this casting.

Quick example

age_text = "25"
age = int(age_text)

price_text = "19.99"
price = float(price_text)

count = 5
count_text = str(count)

print(age + 5)
print(price + 0.01)
print("Count: " + count_text)

Output:

30
20.0
Count: 5

This shows the most common conversions:

  • string to integer with int()
  • string to float with float()
  • number to string with str()

What type conversion means

Every value in Python has a type.

For example:

  • "hello" is a string
  • 10 is an integer
  • 3.14 is a float
  • True is a boolean

Type conversion means changing a value from one type to another.

Python usually does this with built-in functions such as:

  • int()
  • float()
  • str()
  • bool()

Example:

text_number = "42"
number = int(text_number)

print(number)
print(type(number))

Output:

42
<class 'int'>

Why type conversion is needed

Type conversion is needed because data does not always arrive in the type you want.

Common examples:

  • input() always returns a string
  • file contents are often read as text
  • API data may contain numbers as strings
  • math requires number types
  • building messages often requires strings

Example with input():

age_text = input("Enter your age: ")
age = int(age_text)

print(age + 1)

If the user types 25, Python first receives "25" as text.
You convert it with int() so you can do math.

If you want to understand this better, see the input() function explained.

Common conversions beginners use

These are the conversions you will use most often:

  • string to integer with int()
  • string to float with float()
  • integer or float to string with str()
  • other values to boolean with bool()
  • basic sequence conversions with list(), tuple(), set(), and dict()

Example:

print(int("7"))
print(float("2.5"))
print(str(100))
print(bool(1))
print(list("abc"))
print(tuple([1, 2, 3]))
print(set([1, 2, 2, 3]))
print(dict([("a", 1), ("b", 2)]))

Output:

7
2.5
100
True
['a', 'b', 'c']
(1, 2, 3)
{1, 2, 3}
{'a': 1, 'b': 2}

Convert strings to integers

Use int() to convert a string to a whole number.

number = int("10")
print(number)
print(type(number))

Output:

10
<class 'int'>

The string must look like a whole number.

These work:

print(int("42"))
print(int(" 42 "))
print(int("-7"))

Output:

42
42
-7

This fails:

print(int("10.5"))

Error:

ValueError: invalid literal for int() with base 10: '10.5'

That happens because "10.5" is a decimal number, not a whole number string.

If you need more detail, see int() explained or how to convert a string to int in Python.

Convert strings to floats

Use float() to convert a string to a decimal number.

price = float("3.14")
print(price)
print(type(price))

Output:

3.14
<class 'float'>

This is useful when numbers may contain decimal points.

Example:

height_text = "1.75"
height = float(height_text)

print(height * 2)

Output:

3.5

Invalid text causes an error:

print(float("abc"))

Error:

ValueError: could not convert string to float: 'abc'

See float() explained or how to convert a string to float in Python.

Convert numbers to strings

Use str() when you need to combine numbers with text.

This is very common in print() messages, file output, and labels.

score = 95
message = "Your score is " + str(score)

print(message)

Output:

Your score is 95

Without str(), this would fail:

score = 95
print("Your score is " + score)

Error:

TypeError: can only concatenate str (not "int") to str

See str() explained or how to convert int to string in Python.

Convert values to booleans

Use bool() to convert a value to True or False.

This follows Python's truthy and falsy rules.

Examples:

print(bool(0))
print(bool(1))
print(bool(""))
print(bool("hello"))

Output:

False
True
False
True

A very common beginner trap is this:

print(bool("False"))

Output:

True

Why? Because "False" is a non-empty string. In Python, non-empty strings are True.

More examples:

print(bool([]))
print(bool([1, 2]))
print(bool(None))

Output:

False
True
False

For more examples, see bool() explained.

Automatic vs explicit conversion

Python sometimes converts values automatically.

For example, when you mix an integer and a float:

result = 5 + 2.5
print(result)
print(type(result))

Output:

7.5
<class 'float'>

Python automatically turns the result into a float here.

But beginners should usually prefer explicit conversion.

Example:

user_text = "12"
user_number = int(user_text)

print(user_number + 3)

Explicit conversion is better because:

  • it makes your code easier to read
  • it makes the intended type clear
  • it helps you catch mistakes earlier

Errors you may see during conversion

Two common errors appear often.

ValueError

You get a ValueError when text cannot be turned into the number you asked for.

Example:

number = int("hello")

Error:

ValueError: invalid literal for int() with base 10: 'hello'

Another example:

price = float("abc")

If you hit this problem, see how to fix ValueError: invalid literal for int() with base 10.

TypeError

You get a TypeError when you use values in the wrong way.

Example:

age = 25
print("Age: " + age)

Error:

TypeError: can only concatenate str (not "int") to str

This happens because + cannot directly join a string and an integer.

To fix it:

age = 25
print("Age: " + str(age))

See how to fix TypeError: can only concatenate str (not int) to str.

Safe conversion patterns for beginners

When data may be invalid, convert carefully.

Check before converting when possible

If you already know what the value should look like, check it first.

value = "42"

if value.isdigit():
    number = int(value)
    print(number)
else:
    print("Not a whole number")

Use try-except for unsafe input

This is helpful for user input and file data.

value = input("Enter a whole number: ")

try:
    number = int(value)
    print("You entered:", number)
except ValueError:
    print("That was not a valid whole number.")

This prevents your program from crashing if the input is bad.

Keep conversions close to where data is used

This makes code easier to understand.

price_text = "9.99"
total = float(price_text) * 2
print(total)

Instead of waiting many lines before converting, convert near the place where you need the correct type.

Common mistakes

These are some very common beginner mistakes:

  • Trying to convert non-numeric text with int() or float()
  • Forgetting that input() returns a string
  • Using + between a string and an integer
  • Assuming bool("False") becomes False
  • Trying int() on a decimal string like "5.2"

If something is not working, these quick checks help:

print(value)
print(type(value))
print(repr(value))

value = input('Enter a number: ')
print(value.strip())

What these do:

  • print(value) shows the current value
  • print(type(value)) shows its type
  • print(repr(value)) shows hidden spaces or characters more clearly
  • value.strip() removes spaces at the start and end

FAQ

What is type conversion in Python?

It means changing a value from one type to another, such as from a string to an integer.

Is casting and type conversion the same thing in Python?

Beginners often use both terms for the same idea. In Python, this usually means using functions like int(), float(), and str().

Why does input() need conversion?

Because input() always returns text, even if the user types a number.

Why does int("10.5") fail?

Because int() expects a whole number string. Use float("10.5") first if needed.

Why is bool("False") True?

Because any non-empty string is True in Python, even the text "False".

See also