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:
print(str(5.0)) # float to string
print(str(1)) # int to string
print(str(True)) # boolean to string
print(int("5")) # string to int
print(int(2.7)) # float to int (lose decimals)
print(float("6.3")) # string to float
print(float(3)) # int to float
print(bool(1)) # int to boolean
print(bool("True")) # string to boolean
(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¶
float("10")
Q#2¶
str(False)
Q#3¶
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:
print(type("This is a string!"))
print(type(100))
print(type(100.0))
print(type(True))
(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:
print(int("ten"))
(ac_convfunc_2)
Note the error. Keep that in mind! Only strings that use digits can be converted to numbers.