Chapter 2
2.1 The Python shell
2.2 Type conversion
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.
book_rating would be assigned with
4.0
.
x is a float,
42.0
, after the code executes.
float() converts the input number of slices from a string to a float for the pizza order calculation.
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.
float(y) = float(4) = 4.0.The fractional part, 0.5, was removed during the integer conversion, int(x).
2.3 Mixed data types
'5.2'
, a string, and
7
, an integer, is not an accepted operation and leads to an error.
2.4 Floating-point errors
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
b**2 and 4*a*c are evaluated first. Adding space around the - operator makes the order of operations more readable.
"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.
"Happy "
to the variable saying.
The second line has no effect on the program.