Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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.141592653589793

Read 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. 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 remove math. from the function. The program prints the same as before.

  2. 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 with ceil. Import it on the same line as pi, separated by a comma. For 9 guests, the output is Pizzas: 4; the exercise also tries other numbers of guests.

Back

4/8

  1. 1. Importing a Module
  2. 2. Rounding
  3. 3. Quiz: Rounding
  4. 4. Importing with from
  5. 5. Quiz: Imports
  6. 6. Random Numbers
  7. 7. Average and Median
  8. 8. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.