5.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:
- When converting a string to an int, 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.
Q-2: Why would we get an error in the following code block?
print(int('32'))
print(int('Hello'))
int
can convert floating-point values to integers, but it
doesn’t round them — 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:
- 23
- Correct! The int function will truncate the float when it converts it 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.
Q-7: Consider the code below. What prints?
print(int(23.865))
- 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.
Q-8: Consider the code below. What prints?
print(float(23))
You have attempted of activities on this page