Python Arena
Step 1 of 3

A program of several files

Any Python file is a module. Put some functions in a file of their own, and other files can import them exactly as they import math. As programs grow, splitting them into files by topic keeps each file short, and a module of useful functions can be reused in the next program too.

On this site, a program can have several files. The editor shows a tab for each one, and Python starts the program from main.py. Here the file units.py holds two conversion functions, and main.py imports it:

main.py
import units

print(f"{units.km_to_miles(42.195):.1f} miles")
print(f"{units.celsius_to_fahrenheit(21):.1f} F")
units.py
def km_to_miles(km):
    return km * 0.621371


def celsius_to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32
Output
26.2 miles
69.8 F

The module's name is the file's name without .py: the file units.py is the module units. Python looks for it in the same folder as the program (on this site, all the files of a program are in the same folder), and then among the modules of the standard library.

Everything you learned about importing works for your own modules too. The from form brings in chosen names:

main.py
from units import km_to_miles

distance = float(input("Distance in km: "))
print(f"That is {km_to_miles(distance):.1f} miles")
units.py
def km_to_miles(km):
    return km * 0.621371


def celsius_to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32
Input
10
Output
Distance in km: 10
That is 6.2 miles

No .py in the import

The import names the module, not the file. With .py, Python reads the dot as a module inside a module, and can't find one:

main.py
import units.py

print(units.km_to_miles(5))
units.py
def km_to_miles(km):
    return km * 0.621371
Python stops with
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import units.py
ModuleNotFoundError: No module named 'units.py'; 'units' is not a package

One more rule for naming your files: don't give a file the name of a standard module. A file called random.py next to your program would be imported instead of the real random module, and nothing random would work. This site doesn't allow such names, but on your own computer it's an easy mistake to make.

Your task

Challenge 1 of 3

main.py uses the functions in shapes.py, but it doesn't import the module, so it stops with a NameError. Add the import to main.py so the program prints:

20
10.0

Challenge 2

main.py is ready, but the two functions in money.py are still empty. Write them:

  • with_tax(price, percent) returns the price with the tax added: a tax of 24 percent makes 10.0 into 12.4.
  • round_up(amount) returns the amount rounded up to a whole number, with math.ceil. A module can import other modules: put import math at the top of money.py.

For example:

Price without tax: 10
With 24% tax: 12.40
Rounded up to whole euros: 13

Challenge 3

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