Lesson 01-05: Conversion Functions

Learning Target: I can convert datatypes from one type to another.

At times, you will be given datatype in one form, but you’ll want to use it in another. For example, later on you’ll be learning how to use the input() function to get the user to type something in, and that always gives you data as a string. But what if you wanted the user to type in a number? How would you change that string to a number?

The Conversion Functions

You would use conversion functions, which are functions that turn one datatype into another datatype.

Table of the conversion functions:

To convert to a String, use... str()
To convert to a Boolean, use... bool()
To convert to a Float, use... float()
To convert to an Integer, use... int()

You would use these functions by putting the value you want to convert between the parentheses. Try running the example below:

 
1
print(str(5.0)) # float to string
2
print(str(1)) # int to string
3
print(str(True)) # boolean to string
4
print(int("5")) # string to int
5
print(int(2.7)) # float to int (lose decimals)
6
print(float("6.3")) # string to float
7
print(float(3)) # int to float
8
print(bool(1)) # int to boolean
9
print(bool("True")) # string to boolean
10

(ac_convfunc_1)

Here are a few notes for specific type to type conversions:

From To Resulting Effect
any string put quotes around the value
int float put a .0 at the end
float int drop everything after decimal point
string int becomes an int if it looks like a number
string float becomes a float if it looks like a number

Checks for Understanding

Q#1

ch0105-1: What is the resulting datatype of the following expression? float("10")




Q#2

ch0105-2: What is the resulting datatype of the following expression? str(False)




Q#3

ch0105-3: What is the result of the following expression? str(2.3)





The type() Function

There is a function, type(), that will tell you the datatype of a value. Run the following code as an example:

5
 
1
print(type("This is a string!"))
2
print(type(100))
3
print(type(100.0))
4
print(type(True))
5

(ex_typefunc)

This is useful for debugging purposes if you ever need to see the type of a value.

A Note on Errors

So what happens if you try to convert something like a word to an integer? See for yourself:

2
 
1
print(int("ten"))
2

(ac_convfunc_2)

Note the error. Keep that in mind! Only strings that use digits can be converted to numbers.

Next Section - Lesson 01-06: Introduction to Variables