Exercise:08 python variable and its types

 

Type conversion

Using the + operator to paste together two strings can be very useful in building custom messages.

Suppose, for example, that you've calculated the return of your investment and want to summarize the results in a string. Assuming the integer savings and float result are defined, you can try something like this:

print("I started with $" + savings + " and now have $" + result + ". Awesome!")

This will not work, though, as you cannot simply sum strings and integers/floats.

To fix the error, you'll need to explicitly convert the types of your variables. More specifically, you'll need str(), to convert a value into a string. str(savings), for example, will convert the integer savings to a string.

Similar functions such as int()float() and bool() will help you convert Python values into any type.


Instructions
100 XP
  • Hit Run Code to run the code. Try to understand the error message.
  • Fix the code such that the printout runs without errors; use the function str() to convert the variables to strings.
  • Convert the variable pi_string to a float and store this float as a new variable, pi_float.

Question:01.

Can Python handle everything?

Now that you know something more about combining different sources of information, have a look at the four Python expressions below. Which one of these will throw an error? You can always copy and paste this code in the IPython Shell to find out!

Instructions
50 XP
Possible Answers

Comments