2.1 The Python shell
2.2 Type conversion
1.
a.
book_rating
was assigned with
3.5
on line 5 and converted from an integer to a float by the interpreter. book_rating
isn't modified after line 5.
2.
a.
Combining a float and an integer in a calculation produces a float.
book_rating
would be assigned with
4.0
.
3.
a.
A calculation with a float and an integer produces a float.
x
is a float,
42.0
, after the code executes.
4.
a.
float()
converts the input number of slices from a string to a float for the pizza order calculation.
5.
b.
int()
removes any fractional part. Many calculations will produce a fractional part. Ex: 46 people with 3.0 slices per person will need 138 slices or 17.25 pizzas. int(17.25)
is
17
, so adding
1
produces
18
pizzas, a better estimate to ensure enough pizza is ordered.
8.
a.
float(y) = float(4) = 4.0
.The fractional part, 0.5, was removed during the integer conversion, int(x)
.
2.3 Mixed data types
11.
c.
Adding
'5.2'
, a string, and
7
, an integer, is not an accepted operation and leads to an error.
2.4 Floating-point errors
1.
b.
An overflow error occurs because the value is larger than the upper limit of the floating-point range.
2.
a.
The digits starting from the eighteenth place after the decimal are inaccurate due to approximation, so a round-off error occurs.
5.
b.
When
round()
is applied to an integer value without specifying the number of decimal places, there will be no change to the value.
2.5 Dividing integers
2.6 The math module
2.7 Formatting code
4.
a.
The expressions
b**2
and 4*a*c
are evaluated first. Adding space around the -
operator makes the order of operations more readable.
7.
c.
The literal
"Hello,"
and the variable name
cannot be concatenated without using a +
operator.
Alternatively, the two values could be separated by a comma in the print function.
9.
a.
Using one print statement with parentheses joins the lines implicitly and does not increase the number of statements.
10.
c.
The first line assigns
"Happy "
to the variable saying.
The second line has no effect on the program.
2.8 Python careers
1.
d.
Python is one of the most-used programming languages in the world, especially in fields outside of CS and IT.