Importing with from
When a program uses something from a module many times, writing math. in front of every call gets long. With from, you import only the names you need, and then you write them without the module's name:
from math import sqrt, pi
print(sqrt(81))
print(pi)9.0
3.141592653589793Read the first line as “from the module math, import sqrt and pi”. The names are separated by commas, and only these names come into the program: to write floor() as well, you add it to the list. The name math itself isn't imported, so this program ends with an error on its last line:
from math import sqrt, pi
print(sqrt(81))
print(math.sqrt(64))9.0
Traceback (most recent call last):
File "<exec>", line 4, in <module>
NameError: name 'math' is not defined. Did you forget to import 'math'?Which way is better? Both are right, and you'll see both in other people's code. import math keeps the module's name at every call, so you always see where a function comes from, which helps in a long program that uses several modules. from … import is shorter when you use a few names often. Pick one way for each module and keep to it in the whole program.
You'll also meet import … as …, which gives a module another name in your program, usually a shorter one: after import math as m, you write m.sqrt(81). Programmers do that with modules whose names are long.
Instructions
- 1
A party is ordering pizza. Run the program: one 40 cm pizza is more pizza than two 28 cm ones! Now change the first line to
from math import pi, and removemath.from the function. The program prints the same as before. - 2
Each guest eats 3 slices, and a pizza is cut into 8. At the end of the program, print how many pizzas to order for
guests, rounded up withceil. Import it on the same line aspi, separated by a comma. For 9 guests, the output isPizzas: 4; the exercise also tries other numbers of guests.