Python Arena
Step 2 of 3

Importing names with from

Writing math. in front of every name gets long when a program uses the same function many times. The from form of import brings chosen names from a module straight into your program:

from math import sqrt

print(sqrt(81))
print(sqrt(2))
Output
9.0
1.4142135623730951

Now sqrt works on its own, without the prefix. To bring in several names, separate them with commas:

from math import floor, ceil, pi

print(floor(pi))
print(ceil(pi))
print(f"{pi:.2f}")
Output
3
4
3.14

Only what you import

from math import sqrt brings in sqrt and nothing else. The name math itself isn't defined, so math.sqrt fails, and so does any other name of the module that you didn't list:

from math import sqrt

print(sqrt(25))
print(math.sqrt(36))
Output
5.0
Python stops with
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(math.sqrt(36))
          ^^^^
NameError: name 'math' is not defined. Did you forget to import 'math'?

Python's guess is one way to fix it: add import math. The other is to write sqrt(36), the name you did import.

Which form to use

Both forms reach the same functions, so choose by what reads best:

  • import math keeps the module's name in every call. math.floor(x) tells the reader exactly where floor comes from.
  • from math import floor is shorter, which is handy when a program uses a function often.

There's a third form, from math import *, which imports every name the module has. It saves typing, but it hides where the names come from, and it can quietly replace a name of your own. The math module has a value called e (2.718...), so it overwrites a variable e of yours:

e = "Eve"
from math import *

print(e)
Output
2.718281828459045

No error, just a wrong value. Use the star form only for quick experiments, if at all.

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

The program uses three names from the math module, but its import line brings in only one of them, so it stops with a NameError. Change the import line (keep it a from import) so the program works. For example:

Area of the square plot: 50
Side: 7.07
Fence needed, in whole meters: 29
Radius of a round plot of the same area: 3.99

Challenge 3

The math module also has gcd(a, b), the greatest common divisor: the largest whole number that divides both a and b evenly. gcd(6, 8) is 2. Dividing the top and the bottom of a fraction by it gives the fraction in its simplest form: 6/8 is 3/4.

Write a function simplify(top, bottom) that returns the simplest form of the fraction top/bottom as a string, such as "3/4". Import gcd with from.