Academic Block

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 int to a float in a mixed calculation.
  • Explicit conversion: you call a function such as int(), float(), str(), bool(), list(), tuple(), set(), or dict().
  • 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 a ValueError.

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.

What this code does: It adds an integer and a float, and prints the result with its type. It then adds a Boolean to an integer and divides two integers to show that / 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))

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.

What this code does: It converts floats to integers by truncation and by rounding, converts integers and strings to floats, adds a number converted from a string, and reads binary and hexadecimal text as integers.
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))

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.

What this code does: It joins numbers to text using 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]))

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 a range.
  • 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.

What this code does: It turns a string into a list of characters, uses a set to count the distinct letters, converts a list to a tuple, builds a dictionary from pairs, and converts a range to a list.
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)))

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.

What this code does: It reads a price and converts it to a float, reads a quantity and converts it to an integer, calculates the total, and prints it both as a number and as text joined to a sentence.
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print("Total:", total)
print("Total as text: " + str(total))

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.

What this code does: It reads text from the user and tries to convert it to an integer inside a 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.")

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().

What this code does: It converts the text "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))
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: " + 21 raises a TypeError. Use str(21) or an f-string.
  • Forgetting to convert input: input() returns text, so input() * 2 repeats the text instead of doubling a number.
  • Converting a decimal string with int(): int("3.5") raises a ValueError. Use int(float("3.5")).
  • Expecting int() to round: int(3.99) is 3. Use round() when you want the nearest whole number.
  • Trusting bool("False"): any non-empty string is truthy, so bool("False") is True.
  • Not handling bad input: a user can type anything. Catch ValueError when 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(), and str().
  • int() truncates floats, and round() rounds them to the nearest whole number.
  • list(), tuple(), set(), and dict() convert between collections, and set() removes duplicates.
  • input() always returns a string, so convert it before calculating.
  • A failed conversion raises a ValueError that you can catch with try and except.

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.

Ready for the next step?Learn how to read input from users and display output.
Next: Input & Output →