Python Type Conversion
Table of Contents + β
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 + 1print(result)Output
6Letβ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 number5.number + 1now works, becausenumberis a real number. It gives6.print(result)shows6.
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.0So 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 = 25message = "Riya is " + str(age) + " years old."print(message)Output
Riya is 25 years old.Here is what happens:
age = 25is 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 texta = "10"b = "5"print(a + b)Output
105See 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 adda = "10"b = "5"print(int(a) + int(b))Output
15Now 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
FalseFalseTrueTrueReading the results:
bool(0)isFalse, because zero counts as empty.bool("")isFalse, because an empty string has nothing in it.bool(42)isTrue, because it is a real number that is not zero.bool("hello")isTrue, 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 aValueError. 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 numberint("hello") # ValueError: invalid literal for int() with base 10: 'hello'
# β
Good: the text looks like a numberint("42") # 42- Using
int()on a decimal string.int()cannot read a string that has a decimal point. Soint("3.5")raises aValueError. Usefloat("3.5")instead. You can doint(3.5)on the number though. It cuts off the decimal and gives3. - 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, likex = 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 andfloat()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(), andbool(). - β User input always arrives as a string, so convert it before doing math.
- β
int()andfloat()turn text into numbers, andstr()turns a number into text. - β
Adding two number-strings with
+joins them as text, so"10" + "5"gives"105", not15. - β
int("hello")raises aValueError, because the text is not a number.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 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
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
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
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.