Types and type conversions

Question Click to View Answer

What does the following code return?

type(2)

<class 'int'> is returned.

2 is an instance of the int class.

What does the following code return?

type(3.5)

<class 'float'> is returned.

3.5 is as instance of the float class.

What does the following code return?

type(False)

<class 'bool'> is returned.

False is an instance of the bool class.

What does the following code return?

isinstance(2, int)

True is returned because 2 is an instance of the int class.

What does the following code return?

isinstance(False, bool)

True is returned because False is an instance of the bool class.

What does the following code return?

int("7") == 7

True is returned.

The int() function converts a string into an integer.

What does the following code return?

int("happy")

This code raises a ValueError with the following message: invalid literal for int() with base 10: 'happy'.

The "happy" string cannot be converted into an integer, so Python raises an error.

What does the following code return?

bool(1)

True is returned.

The integer 1 is converted to True by the bool() function. The integer 0 is converted to False by the bool() function (i.e. bool(0) == False).

What does the following code return?

str("42")

42 is returned.

The str() function converts a string to an integer.

What does the following code return?

2 + 3

5 is returned.

The + operation performs addition when both of the operands are integers.

What does the following code return?

4 + 5.0

9.0 is returned.

Notice that 9.0 is returned, not 9.

The + operator returns a floating point number when one operand is an integer and the other operand is a floating point number.

What does the following code return?

"cat" + "dog"

"catdog" is returned.

The + operator performs string concatenation when both arguments are strings.

What does the following code return?

"cup" + 1

This code raises a TypeError with the following message: must be str, not int.

Python cannot perform string concatenation when one operand is a string and the other operand is an integer, so it raises an error.

What does the following code return?

"hi" + str(5)

'hi5' is returned.

The str() function is used to convert 5 into "5".

String concatenation can be performed once the integer 5 is converted to a string.