Section 6.3 Type conversion functions
Python also provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or complains otherwise:
Checkpoint 6.3.1.
Q-2: Why would we get an error in the following code block?
print(int('32'))
print(int('Hello'))
When converting a string to an integer, we must remove the quotation marks.
Incorrect! This would only work if Hello
was a variable name with a value of the correct type. For example, Hello = '32'
. Try again.
The int
function is expecting a value that can be converted to an integer.
Correct! The int
function expects a value that can be converted, and strings cannot be converted to integers.
We cannot print and call a function in the same line.
Incorrect! This is actually possible—it worked with the first line. Try again.
int
can convert floating-point values to integers, but it doesn’t round them. Instead, it chops off the fraction part (this is called truncating):
float
converts integers and strings to floating-point numbers:
Finally, str
converts its argument to a string:
Checkpoint 6.3.2.
Checkpoint 6.3.3.
Q-7: Consider the code below. What prints?
23
Correct! The int
function will truncate the decimal places when it converts the value to an integer.
24
Incorrect! The int
function doesn’t round up. Try again.
2
Incorrect! The int
function doesn’t only convert the first digit. Try again.
23.8
Incorrect! The int
function doesn’t keep any of the decimal places. Try again.
Checkpoint 6.3.4.
Q-8: Consider the code below. What prints?
24.0
Incorrect! The float
function will be the same value as the integer. Try again.
2.3
Incorrect! The float
function will not split a multi-digit integer. Try again.
23.0
The float
function will add ".0" to the end of an integer, turning it into a floating point number.
23
Incorrect! Floating point numbers have a decimal point in them. Try again.