4.2. Type Conversion¶
Sometimes it is necessary to convert values from one type to another. A common
example occurs when a program receives string input, like
"23", but needs
to use the value as a number.
Python provides a few simple type conversion functions that allow us to
change between data types. The functions
will try to convert whatever is in the
() (the argument) into the types
int() function takes a floating point number or a string and turns it
into whole number. Instead of rounding a decimal value,
the decimal portion of the number.
int() in action. Run the following code and note how
changes the decimal values.
New vocabulary! Truncate: Remove the decimal part of a number WITHOUT rounding.
What happens if we try to convert a string to an integer, but the string is not actually a whole number? Add the following code to the editor above, then run the program again. You should see an error message.
In order for
int() to work, the string has to be a whole number like
"526". Any string with letters, spaces, or punctuation will
throw an error. Modify the new examples by deleting the
then rerun the program. You should see the integers
The type converter
float() turns an integer or an allowed string into a
float. The type converter
str() turns its argument into a
Remember that when we print a string, the quotes are removed. However, if we
type() function, we can see the data type.
str() in action.
4.2.1. Check Your Understanding¶
What value is printed when the following statement runs?
print( int(53.785) )
- Nothing is printed. An error is generated.
Which of the following generates an error message when passed to
float()? Feel free to try running each of the options.
- '3 3'