Python Type Conversion
Changing Data Types: Understanding Type Conversion
In Python, data has different types like whole numbers (int
), numbers with decimals (float
), text (str
), or true/false values (bool
). We learned about these basic types in a previous article.
Sometimes, you have a piece of data that is one type, but you need to change it into another type so you can use it in a different way.
Think about these common situations:
- You ask the user to type their age using
input()
.input()
always gives you text (a string), even if they type numbers. But you need a number type to do math with their age. - You have a score as a number and want to show it as part of a sentence. You need to combine the number with text.
- You have a price like
15.75
(float
), but you only need the whole dollar amount15
(int
).
To handle these situations, Python provides type conversion.
What is Type Conversion (or Casting)?
Type conversion is the process of changing an object of one data type into an object of a different data type. It's like transforming data from one form to another so it fits a specific need.
Python has built-in functions that help you do this. These functions are usually named after the type you want to change the data into. For example, int()
is used to convert to an integer, str()
to convert to a string, and float()
to convert to a float.
When you convert a type, you don't change the original object (most basic types are immutable anyway). Instead, Python creates a new object of the target type with the converted value.
Let's look at how to convert values to some common types.
Converting to Different Types
You use built-in functions to perform type conversion.
Converting to a Whole Number (int()
)
The int()
function tries to convert a value into an integer (int
).
-
From a float: When you convert a float to an integer using
int()
, Python simply cuts off the decimal part. It does not round the number up or down.float_value1 = 10.8 int_from_float1 = int(float_value1) # The .8 is cut off print(int_from_float1) # Output: 10 float_value2 = 9.1 int_from_float2 = int(float_value2) # The .1 is cut off print(int_from_float2) # Output: 9
(Remember the
round()
function from the Data Types article if you need to actually round numbers.) -
From a string: When you convert a string to an integer using
int()
, the string must contain only digits and represent a whole number. It cannot have letters, symbols, or a decimal point.string_number = "123" int_from_string = int(string_number) print(int_from_string) # Output: 123 print(type(int_from_string)) # Output: <class 'int'> # What happens if the string is not a valid whole number? # invalid_string1 = "hello" # int(invalid_string1) # This would cause an error! # invalid_string2 = "10.5" # int(invalid_string2) # This would also cause an error!
Trying to convert a string that doesn't look exactly like a whole number will cause a
ValueError
, which means the value's format is incorrect for the type you are trying to convert to.
Converting to a Number with Decimals (float()
)
The float()
function tries to convert a value into a floating-point number (float
).
-
From an integer: Converting an integer to a float is straightforward; Python just adds
.0
to the end.int_value = 25 float_from_int = float(int_value) print(float_from_int) # Output: 25.0 print(type(float_from_int)) # Output: <class 'float'>
-
From a string: When converting a string to a float, the string must represent a valid number, either a whole number or a number with a decimal point.
string_float = "9.99" float_from_string1 = float(string_float) print(float_from_string1) # Output: 9.99 string_int = "100" # A string representing a whole number is fine float_from_string2 = float(string_int) print(float_from_string2) # Output: 100.0 # What if the string is not a valid number? # invalid_string = "world" # float(invalid_string) # This would cause a ValueError!
Converting to Text (str()
)
The str()
function is very versatile. It can convert almost any value in Python into its string representation. This is useful when you need to display a value or combine it with other text.
-
From numbers, booleans, None, and collections:
str()
creates a text version of the object.number_value = 42 text_from_number = str(number_value) print(text_from_number) # Output: "42" (it's now text) print(type(text_from_number)) # Output: <class 'str'> bool_value = True text_from_bool = str(bool_value) print(text_from_bool) # Output: "True" none_value = None text_from_none = str(none_value) print(text_from_none) # Output: "None" list_value = [1, 2, 3] text_from_list = str(list_value) print(text_from_list) # Output: "[1, 2, 3]" (a string that looks like the list)
While you can use
str()
to convert values for joining with the+
operator (e.g.,"Score: " + str(score)
), using f-strings is usually a simpler way to include non-string values directly in print statements (print(f"Score: {score}")
).
Converting to True or False (bool()
)
The bool()
function converts a value into a boolean (bool
) object, either True
or False
. This conversion is based on the "truthiness" or "falsiness" of the value, as discussed in the Data Types article.
-
bool()
returnsFalse
for values considered "falsy".print(bool(False)) # Output: False (obviously) print(bool(None)) # Output: False (absence of value is falsy) print(bool(0)) # Output: False (the number zero is falsy) print(bool(0.0)) # Output: False (zero float is falsy) print(bool("")) # Output: False (an empty string is falsy) print(bool([])) # Output: False (an empty list is falsy) print(bool({})) # Output: False (an empty dictionary is falsy) # ... and other empty collections like tuples, sets
-
bool()
returnsTrue
for values considered "truthy" (almost everything else).print(bool(True)) # Output: True (obviously) print(bool(1)) # Output: True (any non-zero integer) print(bool(-5.5)) # Output: True (any non-zero float) print(bool("hello")) # Output: True (any non-empty string) print(bool([1, 2])) # Output: True (any non-empty list)
You often don't need to call
bool()
explicitly inif
statements, becauseif
automatically checks the truthiness of the value provided (e.g.,if my_list:
is the same asif bool(my_list):
). But thebool()
function shows exactly how Python evaluates a value's truthiness.
Converting Between Collection Types
You can also convert between some collection types using functions like list()
, tuple()
, set()
, and dict()
. This is useful for changing how the collection behaves (e.g., making it mutable or getting unique items).
-
To
list()
: Convert sequences (like strings, tuples, ranges) or other iterables (like sets, dictionaries) into a list. A list is ordered and changeable.tuple_value = (1, 2, 3) list_from_tuple = list(tuple_value) print(list_from_tuple) # Output: [1, 2, 3] string_value = "hello" list_from_string = list(string_value) # Creates a list of characters print(list_from_string) # Output: ['h', 'e', 'l', 'l', 'o'] set_value = {1, 2, 3} list_from_set = list(set_value) # Converts set items to list (order might vary) print(list_from_set) # Output: [1, 2, 3] (order might differ)
-
To
tuple()
: Convert sequences (like strings, lists, ranges) or other iterables (like sets, dictionaries) into a tuple. A tuple is ordered but unchangeable (immutable).list_value = [1, 2, 3] tuple_from_list = tuple(list_value) print(tuple_from_list) # Output: (1, 2, 3) string_value = "world" tuple_from_string = tuple(string_value) # Creates a tuple of characters print(tuple_from_string) # Output: ('w', 'o', 'r', 'l', 'd')
-
To
set()
: Convert sequences (like strings, lists, tuples, ranges) or other iterables into a set. Sets are unordered and only contain unique items (duplicates are removed).list_with_duplicates = [1, 2, 2, 3, 1] set_from_list = set(list_with_duplicates) # Duplicates 1 and 2 are removed print(set_from_list) # Output: {1, 2, 3} (order might vary) string_value = "programming" set_from_string = set(string_value) # Unique characters from the string print(set_from_string) # Output: {'p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'} (order might vary)
(Converting to
dict()
is possible but requires the input to be a sequence of key-value pairs, like a list of two-item tuples[(key1, value1), (key2, value2)]
.)
Putting It Together: Input Requires Conversion
We saw in the Inputs/Outputs article that the input()
function always gives you a string, even if the user types numbers. This is a classic case where you must use type conversion to work with the data correctly.
# 1. Get input from the user (it's always a string)
age_str = input("Please enter your age: ") # Example: user types "30"
# At this point, 'age_str' points to the string object "30".
# You cannot do math like age_str + 5 directly.
# 2. Convert the string input to a number type (int in this case)
# This is where type conversion is essential after input() for numbers.
age_int = int(age_str)
# Now, 'age_int' points to the integer object 30.
# You can do math operations with age_int.
# 3. Use the number for calculations or other number operations
age_next_year = age_int + 1
# 4. Print the result (often involves implicit conversion back to string for display)
print(f"Next year, you will be {age_next_year} years old.")
# If the user typed "30", the output is: Next year, you will be 31 years old.
This pattern of getting input, converting its type, and then processing it is very common in interactive programs.
What Happens if Conversion Fails? (ValueError
)
As hinted earlier, if you try to convert a value that Python cannot reasonably turn into the target type, it will stop your program and give you an error. For conversions like int()
, float()
, and others, this error is typically a ValueError
.
# This will cause a ValueError because "hello" cannot be converted to a number
# invalid_int = int("hello")
# print(invalid_int) # This line is never reached
# This will cause a ValueError because "10.5" is not a pure integer string
# invalid_float_str = "10.5"
# invalid_int_from_float_str = int(invalid_float_str)
# print(invalid_int_from_float_str) # This line is never reached
A ValueError
means the value is wrong for the intended conversion. In real programs, you would use error handling techniques (like try-except
blocks, a topic for a future article) to catch these errors and guide the user instead of letting the program crash.
Conclusion
Type conversion is a fundamental tool in Python that allows you to change data from one type to another. This is necessary to ensure your data is in the correct format for the specific operations you want to perform.
- You learned that built-in functions like
int()
,float()
,str()
,bool()
,list()
,tuple()
,set()
, anddict()
are used for type conversion. - You saw practical examples of converting between basic types (numbers, strings, booleans) and between collection types.
- You reinforced why converting the string output from
input()
is crucial when you need to work with numbers or other types. - You learned that trying an invalid conversion results in a
ValueError
.
Mastering type conversion gives you essential control over your data and is key to writing flexible programs that can handle different kinds of input and manipulate various data types effectively.