Python Type Conversion

In the last lesson you learned Boolean Values, the True and False type. Now let’s solve a problem you will hit very soon. Sometimes a value is the wrong type for what you want to do with it. A number arrives as text. Your math breaks. Type conversion is how you fix that.

πŸ€” Why do we need type conversion?

Here is the real pain. Python is strict about types. It will not quietly turn text into a number for you. So when a value comes in as the wrong type, your code stops working.

The most common case is user input. When a person types something, Python hands it to you as a string. A string is text in quotes. Even if they type 5, you get the string "5". You do not get the number 5. So when you try to do math with it, things go wrong.

Type conversion fixes this. It lets you change a value from one type to another. Then the value is the right type for the job.

πŸ”„ What is type conversion?

Type conversion means taking a value of one type and making a new value of another type. People also call it casting. You β€œcast” a string into a number. Or you cast a number into a string.

Think about Alex paying at a shop. The price tag says β€œ5” on a piece of paper. That is text. To add it to other prices in a calculator, Alex first reads it as the number five. He converts the written β€œ5” into a real number he can add. That mental step is exactly what casting does in code.

Python gives you a small set of built-in functions for this. Each one is named after the type it makes.

Function Turns a value into Example
int() a whole number int("5") gives 5
float() a decimal number float("3.5") gives 3.5
str() text (a string) str(5) gives "5"
bool() True or False bool(0) gives False

You wrap the value inside the brackets. You get back a brand new value of that type. The original value does not change. You get a fresh one.

πŸ”’ Turning text into a number with int() and float()

Let’s start with the most useful one. You have text that looks like a number. You want to actually do math with it.

This code takes the string "5". It converts it to the number 5. Then it adds one.

text_value = "5"
number = int(text_value)
result = number + 1
print(result)

Output

6

Let’s walk through it line by line:

  • text_value = "5" stores the text "5". Notice the quotes. This is a string, not a number.
  • int(text_value) converts that text into the whole number 5.
  • number + 1 now works, because number is a real number. It gives 6.
  • print(result) shows 6.

Use int() when the number is whole. An age or a count is a good fit. Use float() when the number has a decimal point. A price or a measurement is a good fit.

This example reads a height as text. It converts it to a decimal number so we can do math with it.

height_text = "1.75"
height = float(height_text)
print(height + 0.25)

Output

2.0

So int() is for whole numbers. And float() is for decimals. Pick the one that matches the value.

πŸ“ Turning a number into text with str()

Now the other direction. Sometimes you have a number and you want to put it inside a message. The problem is you cannot join a number and a string directly with +. Python will not mix the two types.

This is where str() helps. It turns a number into text. Then you can build a sentence.

age = 25
message = "Riya is " + str(age) + " years old."
print(message)

Output

Riya is 25 years old.

Here is what happens:

  • age = 25 is a number.
  • str(age) turns that number into the text "25".
  • Now all three parts are strings, so + can join them into one sentence.

Without str(age), Python would stop and complain. You cannot add a number to text. The str() call makes the number safe to join.

f-strings convert for you

Modern Python has an easier way to put numbers in text. It is called an f-string. You write f"Riya is {age} years old." and Python converts age to text for you. You will use f-strings a lot. But it helps to know str() is doing the same job underneath.

πŸ› The classic input-is-a-string bug

This is the mistake almost everyone makes once. So let’s see it clearly now. Then you can skip the pain later.

When a person types a number, Python gives you a string. So if you add two of them, you do not get math. You get the two pieces of text stuck together.

# ❌ Avoid: a and b are strings, so + joins them as text
a = "10"
b = "5"
print(a + b)

Output

105

See that? You expected 15. But you got 105. Python glued "10" and "5" together as text. That joining is called concatenation. It is what + does to strings.

The fix is to convert each one to a number first. Then add.

# βœ… Good: convert to numbers, then add
a = "10"
b = "5"
print(int(a) + int(b))

Output

15

Now int(a) is 10 and int(b) is 5. So + does real math and gives 15. Whenever a number arrives as text, convert it before you do any math.

βœ… True or False with bool()

The bool() function turns a value into True or False. It follows one simple idea. β€œEmpty or zero” becomes False. Everything else becomes True.

This code shows what counts as False.

print(bool(0))
print(bool(""))
print(bool(42))
print(bool("hello"))

Output

False
False
True
True

Reading the results:

  • bool(0) is False, because zero counts as empty.
  • bool("") is False, because an empty string has nothing in it.
  • bool(42) is True, because it is a real number that is not zero.
  • bool("hello") is True, because the string has text in it.

You will see this idea again when you learn if statements. There Python checks if something is β€œtruthy” or β€œfalsy”.

⚠️ Common Mistakes

A few things trip people up with conversion. Watch for these.

  • Converting text that is not a number. int("hello") raises an error called a ValueError. The reason is that "hello" is not a number Python can read. Only convert text that really looks like a number.
# ❌ Avoid: "hello" is not a number
int("hello") # ValueError: invalid literal for int() with base 10: 'hello'
# βœ… Good: the text looks like a number
int("42") # 42
  • Using int() on a decimal string. int() cannot read a string that has a decimal point. So int("3.5") raises a ValueError. Use float("3.5") instead. You can do int(3.5) on the number though. It cuts off the decimal and gives 3.
  • Forgetting to convert input. A value typed by a person is always a string. If you skip the conversion, your math joins text instead of adding numbers.
  • Thinking conversion changes the original. It does not. int(x) gives you a new value. If you want to keep it, store it, like x = int(x).

int() does not round, it cuts

When you do int() on a decimal number, it does not round. int(3.9) gives 3, not 4. It just drops everything after the dot. If you want proper rounding, use round() instead.

βœ… Best Practices

  • Convert user input the moment you receive it. Then the rest of your code has the right type.
  • Pick int() for whole numbers and float() for decimals. Match the function to the value.
  • Before converting text to a number, be sure it actually looks like one. Or be ready for a ValueError.
  • Use f-strings for messages. They convert numbers to text for you and read more cleanly than lots of str() calls.

🧩 What You’ve Learned

You can now move a value from one type to another. Here is the short version.

  • βœ… Type conversion (casting) changes a value from one type to another, using int(), float(), str(), and bool().
  • βœ… User input always arrives as a string, so convert it before doing math.
  • βœ… int() and float() turn text into numbers, and str() turns a number into text.
  • βœ… Adding two number-strings with + joins them as text, so "10" + "5" gives "105", not 15.
  • βœ… int("hello") raises a ValueError, because the text is not a number.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does int("5") + 1 give?

    Why: `int("5")` converts the text to the number 5, so 5 + 1 does real math and gives 6.

  2. 2

    Why does "10" + "5" give "105" instead of 15?

    Why: When both sides of + are strings, Python concatenates them as text. You must convert each to a number first.

  3. 3

    Which function turns the number 25 into the text "25"?

    Why: `str()` converts a value into a string, so `str(25)` gives the text "25", which you can join into a message.

  4. 4

    What happens when you run int("hello")?

    Why: `"hello"` is not a number Python can read, so `int()` raises a ValueError. Only convert text that looks like a number.

πŸš€ What’s Next?

You know how to fix a value when it is the wrong type. The most common place you will need this is with input typed by a person. Let’s learn how to ask for that input.

Getting User Input

Share & Connect