2.9 Chapter summary
Highlights from this chapter include:
- Expressions and statements can be run interactively using a shell.
- Input strings can be converted to other types. Ex:
int(input). - Strings can be concatenated with other types. Ex:
"$" + str(cost). - Floats are subject to round-off and overflow errors.
- Integers can be divided exactly using
//and%. - Modules like
mathprovide many useful functions. - Formatting long lines helps improve readability.
At this point, you should be able to write programs that ask for input of mixed types, perform mathematical calculations, and output results with better formatting. The programming practice below ties together most topics presented in the chapter.
| Function | Description |
|---|---|
abs(x) | Returns the absolute value of x. |
int(x) | Converts x (a string or float) to an integer. |
float(x) | Converts x (a string or integer) to a float. |
str(x) | Converts x (a float or integer) to a string. |
round(x, ndigits) | Rounds x to ndigits places after the decimal point. If ndigits is omitted, returns the nearest integer to x. |
| Operator | Description |
s * n(Repetition) | Creates a string with n copies of s.
Ex: "Ha" * 3 is "HaHaHa". |
x / y(Real division) | Divides x by y and returns the entire result as a float.
Ex: 7 / 4 is 1.75. |
x // y(Floor division) | Divides x by y and returns the quotient as an integer.
Ex: 7 // 4 is 1. |
x % y(Modulo) | Divides x by y and returns the remainder as an integer.
Ex: 7 % 4 is 3. |