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:

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")
  • (A) int
  • Which conversion function is being used?
  • (B) float
  • Nice job!
  • (C) string
  • Which conversion function is being used?

Q#2

    ch0105-2: What is the resulting datatype of the following expression? str(False)
  • (A) int
  • Which conversion function is being used?
  • (B) float
  • Which conversion function is being used?
  • (C) string
  • Nice job!

Q#3

    ch0105-3: What is the result of the following expression? str(2.3)
  • (A) 2
  • What's the rule when the str() function is used?
  • (B) "2.3"
  • Nice job!
  • (C) 2.3
  • What's the rule when the str() function is used?
  • (D) "2"
  • What's the rule when the str() function is used?

The type() Function

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

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:

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