A Answers to Exercises
Chapter 1 Solutions
-
How do you convert between the different Python data types? What data quality issues arise when converting data types?
You convert between types using the type functions. Thus, to convert a float or string to an integer, you use the
int()
type function. To convert an object to a string, you use thestr()
type function. And so on.When making the conversion, it is possible that you might lose some data in the process. For example, converting a floating-point number to an integer loses the decimal part of the number (for example,
int(2.3)
results in2
). If it’s important to retain the detail, you must retain a copy of the original as well. -
Which of the Python collection types can be used as the key in a dictionary? Which of the Python data types can be used as a value in a dictionary?
Dictionary keys must be immutable. That means that of the basic Python types, integers, booleans, floats, strings, and tuples can all be used as keys (although floats are not recommended due to their imprecision, especially if you will be computing the key value rather than just storing it). Other custom types, such as
frozenset
, can also be used as keys provided they are immutable.Dictionary values can be of any type regardless of mutability.
-
Write an example program using an if/elif chain involving at least four different selection expressions.
You could use any number of choices here. This example uses colors. Your
if/elif/else
code should look ...
Get Python Projects now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.