Python course · Module 2: Values · Lesson 8 of 63
Quick answer: Python type conversion means turning a value of one type into another with int(), float(), str() or bool(). For example, int("21") gives the number 21, and str(21) gives the text "21". If the text is not a valid number, like int("3.5") or int("twenty"), Python stops with a ValueError. Booleans are the two values True and False, and None is a special value that means “no value”.
In this lesson you will learn:
- what
TrueandFalseare and where they come from - which values count as “true” or “false” (truthiness), including a famous trap
- what
Nonemeans and how to check for it - how to convert between
int,float,strandbool, and what each conversion really does - how to read the
ValueErrorandTypeErrormessages that bad conversions give
Before you start: finish Lesson 7, Python Strings and f-Strings. All examples were run as scripts with Python 3.14.6, and Python 3.15.2, the newest release on python.org, gave the same output.
Table of Contents
Booleans: True and False
A Boolean (type bool) has only two possible values: True and False. Both start with a capital letter. Our running example is a sign-up form for a student, Ayesha.
age = 21
is_member = True
print(is_member, type(is_member))
print(age >= 18)
print(age > 30)
can_vote = age >= 18
print("Can vote:", can_vote)
True <class 'bool'>
True
False
Can vote: True
You can type True yourself, but most Booleans come from a comparison. age >= 18 asks a yes/no question, and the answer is True or False. You can store the answer in a variable, like can_vote. In Lesson 11 you will use these answers with if to make decisions.
True and False are secretly 1 and 0
print(True + True)
print(True * 10)
print(int(True), int(False))
2
10
1 0
The standard types page explains that “bool is a subclass of int“, so in maths True behaves like 1 and False like 0. The same page says relying on this “is discouraged”; convert with int() when you really need a number.
Truthiness: what counts as true?
Every value in Python can be treated as true or false. The bool() function shows which one.
print(bool(0), bool(0.0), bool(""), bool(None))
print(bool(42), bool(-1), bool(0.5), bool("hello"))
print(bool(" "), bool("0"), bool("False"))
False False False False
True True True True
True True True
The standard types page lists the values that are false: None and False, “zero of any numeric type”, and empty sequences and collections such as the empty string ''. Everything else is true. So:
0,0.0,""(empty text) andNoneare false.- Any other number, even a negative one, is true.
- Any text with at least one character is true.
That last rule hides a trap. " " (one space), "0" and "False" are all true, because they are not empty. bool() does not read the meaning of the words; it only checks if the string is empty.
None: the “no value” value
None means “nothing here yet” or “no value”. The built-in constants page describes it as “an object frequently used to represent the absence of a value”.
phone = None
print(phone)
print(type(phone))
print(phone is None)
result = print("Saving...")
print(result)
None
<class 'NoneType'>
True
Saving...
None
phone = Nonesays “this student has not given a phone number”. This is different from0or"": those are real values, whileNonemeans there is no value at all.Noneis the only value of the typeNoneType.- To check for
None, useis None. PEP 8 says comparisons toNone“should always be done withisoris not, never the equality operators”. Lesson 9 explainsis. - A function that returns nothing gives back
None.print()shows text on the screen, but its result isNone.
Automatic conversion: int and float
Python converts a few types by itself. When you mix int and float in a calculation, the int becomes a float:
print(3 + 2.5)
print(True + 2.5)
print(type(10 / 2))
5.5
3.5
<class 'float'>
This automatic conversion only happens between number types (and bool, which counts as a number). In a calculation, Python never turns text into a number, or a number into text, by itself. (print() and f-strings do show numbers as text, but only for display; the value itself is not changed.) For everything else you convert yourself.
Converting with int(), float(), str() and bool()
Text from a form, a file or the keyboard always arrives as a string, even when it looks like a number. Watch what + does with text:
age_text = "21"
height_text = "5.6"
print(age_text + age_text)
age = int(age_text)
height = float(height_text)
print(age + age)
print(height * 2)
print(type(age), type(height))
print(str(21) + " years")
print(str(5.6), str(True), str(None))
2121
42
11.2
<class 'int'> <class 'float'>
21 years
5.6 True None
"21" + "21" joins two strings and gives 2121. After int(), the same values add up to 42. The four conversion functions are:
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | whole number | int("21") | 21 |
float() | decimal number | float("5.6") | 5.6 |
str() | text | str(21) | "21" |
bool() | True or False | bool("") | False |
A conversion makes a new value. age_text is still the string "21"; age is a new int.
What int() and float() really do
print(int(3.99))
print(int(-3.99))
print(round(3.99))
print(int(" 42 "))
print(float(" 7.5\n"))
print(int(float("3.5")))
print(float(10))
3
-3
4
42
7.5
3
10.0
int()on a float cuts off the decimal part. It does not round. The built-in functions page says that for floats it “truncates towards zero”, soint(3.99)is3andint(-3.99)is-3. Useround()if you want the nearest whole number.- Spaces and a new line around the number are fine. The same page says the string may “be surrounded by whitespace”.
int()only reads whole-number text. To turn"3.5"into an int, convert to float first:int(float("3.5")).
Putting it together: the sign-up form
name = "Ayesha"
age_text = "21"
fee_text = "1500.50"
newsletter_text = "yes"
age = int(age_text)
fee = float(fee_text)
newsletter = newsletter_text == "yes"
print(f"{name} is {age}, next year {age + 1}.")
print(f"Fee for 2 months: {fee * 2:.2f}")
print("Newsletter:", newsletter, type(newsletter))
Ayesha is 21, next year 22.
Fee for 2 months: 3001.00
Newsletter: True <class 'bool'>
Look at the last conversion. We did not write bool(newsletter_text), because bool("no") would also be True. Instead, newsletter_text == "yes" compares the text and gives a real True or False.
When conversion fails: ValueError and TypeError
If the text is not a valid number, the conversion stops the program with a ValueError:
print(int("3.5"))
Traceback (most recent call last):
File "/home/learner/python-course/err1_int_decimal_text.py", line 1, in <module>
print(int("3.5"))
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'
“Invalid literal for int() with base 10” means “this text is not a whole number”. The message shows the exact text it got, here '3.5'. Words and commas fail the same way:
age = int("twenty")
Traceback (most recent call last):
File "/home/learner/python-course/err2_int_word.py", line 1, in <module>
age = int("twenty")
ValueError: invalid literal for int() with base 10: 'twenty'
price = float("1,500")
Traceback (most recent call last):
File "/home/learner/python-course/err3_float_comma.py", line 1, in <module>
price = float("1,500")
ValueError: could not convert string to float: '1,500'
A TypeError is different: it means the type of the value cannot be converted at all, as with None:
phone = None
print(int(phone))
Traceback (most recent call last):
File "/home/learner/python-course/err5_int_none.py", line 2, in <module>
print(int(phone))
~~~^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
You will learn to catch these errors with try and except in Lesson 35, so a program can ask again instead of stopping.
Try it yourself
Exercise 1: Numbers from text
A shop form gives price_text = "250" and quantity_text = "4". Convert both and print 4 x 250 = 1000 with an f-string.
Exercise 2: Predict the truth
Before you run it, write down True or False for each value: 0, "0", "", " ", 0.0, None, -5, "no". Then check with bool().
Exercise 3: Fix the conversion
This script stops with ValueError: invalid literal for int() with base 10: '62.5'. Fix it so it prints the weight as a float, then rounded to a whole number.
weight_text = "62.5"
weight = int(weight_text)
print(weight)
Solutions
Solution 1
price_text = "250"
quantity_text = "4"
price = int(price_text)
quantity = int(quantity_text)
print(f"{quantity} x {price} = {price * quantity}")
4 x 250 = 1000
Without int(), price_text * quantity_text fails with TypeError: can't multiply sequence by non-int of type 'str', because two strings cannot be multiplied.
Solution 2
print(bool(0), bool("0"), bool(""), bool(" "))
print(bool(0.0), bool(None), bool(-5), bool("no"))
False True False True
False False True True
Only zero, empty text and None are false; "0", " " and "no" are non-empty strings, so they are true.
Solution 3
weight_text = "62.5"
weight = float(weight_text)
print(weight)
print(round(weight))
print(int(weight))
62.5
62
62
float() reads the decimal text. round(62.5) gives 62, not 63: as you saw in Lesson 6, halves round to the even number.
Common mistakes
- Using
bool()on yes/no text.bool("False")andbool("no")are bothTrue, because the strings are not empty. Compare the text instead:answer == "yes". - Converting decimal text with
int().int("3.5")givesValueError: invalid literal for int() with base 10: '3.5'. Usefloat(), orint(float("3.5"))if you need a whole number. - Forgetting to convert before maths.
"21" + 1givesTypeError: can only concatenate str (not "int") to str, and"21" + "21"quietly gives2121. Convert withint()first. - Expecting
int()to round.int(3.99)is3. Useround(3.99)for4. - Converting empty text.
int("")givesValueError: invalid literal for int() with base 10: ''. This happens when a user presses Enter without typing anything.
Frequently asked questions
How do I convert a string to an int in Python?
Pass the string to int(): int("21") returns 21. The text must be a whole number, optionally with a + or - sign and spaces around it. For text with a decimal point, use float() instead.
Why does bool(“False”) return True in Python?
bool() on a string only checks whether the string is empty. "False" has five characters, so it is true. Only the empty string "" is false. To turn yes/no text into a Boolean, compare it, for example text == "True".
What is the difference between None, 0 and an empty string?
0 is a number and "" is a piece of text with no characters; both are real values. None means there is no value at all, and it has its own type, NoneType. All three count as false in bool(), so check for None with is None when the difference matters.
Summary
TrueandFalseare the twoboolvalues; comparisons such asage >= 18produce them.0,0.0,"",Noneand other empty values are false; everything else is true, including"0"and"False".Nonemeans “no value”; check it withis None.- Convert with
int(),float(),str()andbool();int()cuts off decimals instead of rounding. - Bad text gives
ValueError: invalid literal for int() with base 10, and the wrong type gives aTypeError.
Related lessons: Python numbers, Python input() and print(), Python if, elif and else.
Next lesson
Next: Lesson 9, Python Operators: Comparison, Logical, is vs == and Precedence.
Sources
- Built-in Types: truth value testing, numeric types and bool (Python docs)
- Built-in Functions: int(), float(), bool() (Python docs)
- Built-in Constants: True, False and None (Python docs)
- PEP 8: Style Guide for Python Code, programming recommendations
- Python downloads page (python.org)





