2.3. Type conversion functions

Sometimes it is necessary to convert values from one type to another. Python provides a few simple functions that will allow us to do that. The global functions int, float and str will (attempt to) convert their arguments into types int, float and str respectively. We call these type conversion functions.

The type converter str turns its input into a string. Recall that the string concatenation operator, +, requires both operands to be strings. By using the str function it is possible to concatenate a number and a string by first converting the number to a string. This is really useful when you want to print the value of a variable with text.

 
1
number: float
2
text: str
3
4
number = 12.3
5
text = "The value of the number variable is " + str(number)
6
print(text)
7

(ch02_22)

Note

Note that the str function has a higher precidence than the + operator. So 12.3 is converted to a string before is it concatenated.

The type converter float can turn an integer, a float, or a syntactically legal string into a float.

10
 
1
text: str
2
number: float
3
total: float
4
5
text = "12.3"
6
number = float(text)  # convert text from a string to a float
7
total = number + 1.0  # because it is now a float we can perform arithmetic
8
print(number)
9
print(total)
10

(ch02_21)

The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the decimal portion of the number - a process we call truncation towards zero on the number line. Let us see this in action:

7
 
1
print(int(3.14))
2
print(int(3.9999))           # This doesn't round to the closest int!
3
print(int(-3.999))           # Note that the result is closer to zero
4
5
print(int("2345"))           # Parse a string to produce an int
6
print(int("23bottles"))      # Error: invalid input
7

(ch02_20)

The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of those pesky runtime errors. Modify the example by deleting the bottles and rerun the program. You should see the integer 23.

Note

Note that just like in math equations parentheses determine the order of execution. Inner parenthesis are executed first. So print(int(3.14)) will first convert 3.14 to an integer, then it will print it.

Check your understanding

data-3-1: What value is printed when the following statement executes?

print(int(53.285))





data-3-2: What value is printed when the following statement executes?

print(int(53.785))





data-3-3: What value is printed when the following statement executes?

print(int(-53.785))





You have attempted 1 of 7 activities on this page
2.2. Values and Data Types"> 2.4. Variables">Next Section - 2.4. Variables