Python Type ConversionGet Certified
What Is Type Conversion?
Type conversion means changing a value from one data type to another, for example turning the text "42" into the number 42, or a number into a string so it can be joined to a sentence. It is also called type casting. Conversion is needed all the time, because data arrives in one form, such as text typed by a user or read from a file, and the program needs it in another form to calculate with it.
Python converts types in two ways. Sometimes Python does it for you automatically, which is called implicit conversion. In every other case you ask for it with a conversion function such as int() or str(), which is called explicit conversion.
- Implicit conversion: Python converts a value by itself when it is safe, such as an
intto afloatin a mixed calculation. - Explicit conversion: you call a function such as
int(),float(),str(),bool(),list(),tuple(),set(), ordict(). - A new object: a conversion function returns a new value. It does not change the original variable.
- Not always possible: converting
"abc"to an integer fails with aValueError.
Implicit Type Conversion
When an expression mixes numeric types, Python converts the “smaller” type to the “larger” one so that no information is lost. The order is bool to int to float to complex. For example, adding an integer and a float gives a float. The division operator / always returns a float, even when both operands are integers.
Python never converts between text and numbers on its own. Adding "3" + 4 raises a TypeError, because Python cannot guess whether you meant 34 or 7.
Try It: Python Converts Numbers Automatically
Click Test My Code and look at the type of each result. Then change b to 3 and run it again to see the result become an integer.
/ always gives a float.a = 5
b = 2.5
result = a + b
print(result, type(result))
print(True + 4)
print(7 / 7, type(7 / 7))a = 5 stores an int.b = 2.5 stores a float.5 to 5.0 behind the scenes and then adds the two floats. The result, 7.5, is stored in result.7.5 <class 'float'>. The result is a float because that is the larger of the two types.True is converted to 1, so the sum is 5.7 / 7 is 1.0, not 1. The output is 1.0 <class 'float'>.Explicit Conversion to Numbers: int() and float()
The int() function converts a value to a whole number. When given a float, it truncates, which means it cuts off the decimal part without rounding, so int(3.99) is 3 and int(-3.99) is -3. When given a string, the text must look exactly like a whole number. A second argument sets the number base, so int("1010", 2) reads the text as binary.
The float() function converts a number or a numeric string to a decimal number. If you want to round rather than cut, use round(). Note that round() uses “round half to even”, so round(2.5) is 2 and round(3.5) is 4.
Try It: int(), float() and round()
Click Test My Code and compare truncating with rounding.
print(int(3.99), int(-3.99))
print(round(3.99), round(2.5), round(3.5))
print(float(7), float("2.50"))
print(int("42") + 8)
print(int("1010", 2), int("ff", 16))int() drops the decimal part and moves toward zero. The output is 3 -3.round(3.99) is 4. For 2.5, which is exactly halfway, Python rounds to the nearest even number, giving 2, while 3.5 gives 4. The output is 4 2 4.float(7) gives 7.0, and float("2.50") reads the text and gives 2.5. The output is 7.0 2.5.int("42") turns the text into the number 42, so adding 8 gives 50."1010" in base 2 is 10, and "ff" in base 16 is 255. The output is 10 255.Explicit Conversion to Strings: str()
The str() function converts almost any value to text. This is how you combine a number with a piece of text using the + operator. A more convenient way is an f-string, written with an f before the opening quote. An f-string converts the values inside curly braces to text for you.
Try It: Numbers to Text
Click Test My Code. Try deleting str() from the second line and see what error Python reports.
str() and using an f-string. It also converts a Boolean, None, and a list to their text form.age = 21
price = 9.99
print("Age: " + str(age))
print("Price: " + str(price))
print(f"{age} years, ${price}")
print(str(True), str(None), str([1, 2]))age refers to the integer 21.price refers to the float 9.99.str(age) returns the text "21", which can be joined to another string with +. Without str(), Python raises a TypeError. The output is Age: 21.Price: 9.99.f before the quotation mark turns the string into an f-string. Python replaces {age} and {price} with their text. The output is 21 years, $9.99.str() works on Booleans, None, and lists too. The output is True None [1, 2].Converting Between Collections
The collection types can be converted into each other, which is a handy way to change how data behaves:
list(x): builds a list from any iterable, such as a string, a tuple, a set, or arange.tuple(x): builds an unchangeable copy of the items.set(x): removes duplicates. The order of the items is not guaranteed.dict(x): builds a dictionary from a sequence of key-value pairs.list(range(a, b)): turns a range into a real list of numbers.
Try It: Converting Collections
Click Test My Code. Notice that the word "hello" becomes a list of its letters, and that the set holds only four letters because l appears twice.
letters = list("hello")
print(letters)
unique = set(letters)
print(len(unique))
pair = tuple([1, 2, 3])
print(pair)
pairs = [("a", 1), ("b", 2)]
print(dict(pairs))
print(list(range(1, 6)))list("hello") takes the string one character at a time and builds a list of five items.['h', 'e', 'l', 'l', 'o'].set(letters) keeps only one copy of each value, so the repeated "l" is stored once.len(unique) is 4, because the distinct letters are h, e, l, and o.tuple([1, 2, 3]) creates a tuple with the same items. The tuple cannot be changed afterwards.(1, 2, 3).dict(pairs) builds the dictionary, and the output is {'a': 1, 'b': 2}.range(1, 6) produces the numbers 1 to 5. list() turns them into a real list, so the output is [1, 2, 3, 4, 5].Converting User Input
The input() function always returns a string. To calculate with what the user types, convert it right away: int() for whole numbers, float() for numbers that may have decimals. Wrapping the call, as in int(input("Age: ")), is the most common pattern in beginner programs.
Try It: A Price Calculator
The Program Input box is already filled with a price of 12.5 on the first line and a quantity of 4 on the second line. Click Run Code straight away, then change the values and run it again.
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print("Total:", total)
print("Total as text: " + str(total))input() reads the first line of the Program Input box as text, and float() converts it to the decimal number 12.5.4 with int().50.0.print() converts the number to text for display. The output is Total: 50.0.str(total) converts the number to the string "50.0" so that it can be joined with +. The output is Total as text: 50.0.When Conversion Fails: ValueError
A conversion fails when the value cannot be interpreted as the requested type. For example, int("abc") and float("hello") raise a ValueError. The text "3.5" also cannot be converted by int() directly, because it is not written as a whole number. To read it, convert to a float first and then to an integer, as in int(float("3.5")).
A program that reads user input should expect mistakes. The try and except statement lets you catch the error and respond politely instead of crashing. You will study it fully in the error-handling lessons.
Try It: Handling a Bad Conversion
The Program Input box is filled with 3.5, which int() cannot accept. Click Run Code to see the friendly message. Then change the input to 25 and run it again.
try block. If the conversion succeeds, it prints double the number. If it fails, the except block prints a message instead of stopping the program.text = input("Enter a whole number: ")
try:
number = int(text)
print("Double:", number * 2)
except ValueError:
print("'" + text + "' is not a whole number.")input() reads the first line of the Program Input box and stores it as a string in text.try: tells Python to attempt the indented lines. If an error occurs, Python jumps to the matching except block.int("3.5") fails, because the text is not a whole number. Python raises a ValueError and skips the rest of the try block. With the input 25, the conversion works.25 the output is Double: 50.except ValueError: runs only when a ValueError was raised in the try block.'3.5' is not a whole number.Chaining Conversions and Converting Many Values
You can nest conversion functions. The call int(float("3.99")) first reads the text as a float and then truncates it, while round(float("3.99")) rounds it. To convert every item in a collection, use map() with a conversion function. For example, list(map(int, ["10", "20", "30"])) turns a list of strings into a list of integers.
Try It: Converting a Whole List
Click Test My Code. The second half converts a list of strings to numbers, which lets us add them up with sum().
"3.99" to an integer in two steps, and also rounds it. It then converts a list of strings into a list of integers with map() and prints the list together with the sum.text = "3.99"
print(int(float(text)))
print(round(float(text)))
data = ["10", "20", "30"]
numbers = list(map(int, data))
print(numbers, sum(numbers))text refers to the string "3.99". It looks like a number but is still text.float(text) gives 3.99 and int() truncates it. The output is 3.round() rounds the float to the nearest whole number. The output is 4.data holds three strings that look like numbers.map(int, data) applies int() to each item, and list() collects the results into the list [10, 20, 30].sum() can add them. The output is [10, 20, 30] 60.Tip: Conversion functions never change the variable you give them. Write age = int(age) if you want the variable to hold the converted value from then on.
Common Mistakes with Type Conversion
- Joining a string and a number:
"Age: " + 21raises aTypeError. Usestr(21)or an f-string. - Forgetting to convert input:
input()returns text, soinput() * 2repeats the text instead of doubling a number. - Converting a decimal string with int():
int("3.5")raises aValueError. Useint(float("3.5")). - Expecting int() to round:
int(3.99)is3. Useround()when you want the nearest whole number. - Trusting
bool("False"): any non-empty string is truthy, sobool("False")isTrue. - Not handling bad input: a user can type anything. Catch
ValueErrorwhen you convert text typed by a person. - Forgetting to save the result:
int(x)on its own line does nothing useful. Assign the result to a variable.
Key Takeaways
- Type conversion changes a value from one data type to another and returns a new value.
- Implicit conversion happens automatically between numeric types, following the order bool, int, float, complex.
- Python never converts between text and numbers on its own. Use
int(),float(), andstr(). int()truncates floats, andround()rounds them to the nearest whole number.list(),tuple(),set(), anddict()convert between collections, andset()removes duplicates.input()always returns a string, so convert it before calculating.- A failed conversion raises a
ValueErrorthat you can catch withtryandexcept.
Frequently Asked Questions
What is type conversion in Python?
Type conversion, also called type casting, means changing a value from one data type to another, such as turning the string “42” into the integer 42. Conversion functions like int(), float(), and str() return a new value and leave the original unchanged.
What is the difference between implicit and explicit type conversion?
Implicit conversion is done automatically by Python when it is safe, for example when an integer and a float are added and the result is a float. Explicit conversion is done by the programmer with a function such as int(), float(), or str().
How do I convert a string to an integer in Python?
Use the int() function, for example int(“42”), which returns the number 42. The text must look like a whole number. If it does not, for example “abc” or “3.5”, Python raises a ValueError.
Why does int(“3.5”) cause a ValueError?
The int() function only accepts text that is written as a whole number. The text “3.5” contains a decimal point, so Python refuses it. Convert it to a float first and then to an integer with int(float(“3.5”)), which gives 3.
Does int() round or truncate a float?
It truncates. The int() function removes the decimal part and moves toward zero, so int(3.99) is 3 and int(-3.99) is -3. Use round() when you want the nearest whole number.
How do I convert a number to a string in Python?
Use the str() function, for example str(21), which returns “21”. You can also use an f-string, such as f”Age: {age}”, which converts the values inside the braces to text automatically.
How do I convert a list to a set or a tuple in Python?
Pass the list to set() or tuple(), for example set([1, 2, 2]) or tuple([1, 2, 3]). Converting to a set removes duplicate values, and converting to a tuple creates an unchangeable sequence. To go back, use list().
Why can’t I add a string and a number in Python?
Python does not convert between text and numbers automatically, because it cannot know whether “3” + 4 should give 7 or “34”. It raises a TypeError instead. Convert one side first, using int(“3”) + 4 for a number or “3” + str(4) for text.