Python Type Conversion Exercises
Let’s check out some exercises that will help you really understand the type() function and type conversions in Python.
Exercise 4-a
Using type() function assign the type of the variable to answer_1, then print it.
type() function shows the type of a variable.
You can directly type the type() function inside the print() function or another elegant way of doing this is assigning another variable (such as answer_1) to the type of the first variable and printing that variable inside the print() function.
answer_1 = type(men_stepped_on_the_moon)
Exercise 4-b
Using type() function assign the type of the variable to answer_2, then print it.
type() function shows the type of a variable.
You can directly type the type() function inside the print() function or another elegant way of doing this is assigning another variable (such as answer_2) to the type of the first variable and printing that variable inside the print() function.
answer_2 = type(my_reason_for_coding)
Exercise 4-c
Using type() function assign the type of the variable to answer_3, then print it.
type() function shows the type of a variable.
You can directly type the type() function inside the print() function or another elegant way of doing this is assigning another variable (such as answer_3) to the type of the first variable and printing that variable inside the print() function.
answer_3 = type(global_mean_sea_level_delta_2018)
Exercise 4-d
We will now print the type of boolean data. Later stages in programming, booleans become quite common.
type() function shows the type of a variable.
You can directly type the type() function inside the print() function or another elegant way of doing this is assigning another variable (such as answer_4) to the type of the first variable and printing that variable inside the print() function.
answer_4 = type(staying_alive)
Now let’s see some more exercises about converting data types.
Exercise 4-e
Let's now try to convert a string into an integer.
int() function is useful for converting variables.
int() function won’t work on every variable. It has to be an integer saved in a different type of data such as “10” otherwise you can’t convert “boulevard” to an integer no matter which function you use.
answer_5 = int(my_grade)
Exercise 4-f
Can you convert a float into an integer.
Exercise 4-g
Now let's convert a string into a float.
Exercise 4-h
Finally, str will help you convert a data into a string.