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:
import units
print(f"{units.km_to_miles(42.195):.1f} miles")
print(f"{units.celsius_to_fahrenheit(21):.1f} F")def km_to_miles(km):
return km * 0.621371
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 3226.2 miles
69.8 FThe 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:
from units import km_to_miles
distance = float(input("Distance in km: "))
print(f"That is {km_to_miles(distance):.1f} miles")def km_to_miles(km):
return km * 0.621371
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 3210Distance in km: 10
That is 6.2 milesNo .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:
import units.py
print(units.km_to_miles(5))def km_to_miles(km):
return km * 0.621371Traceback (most recent call last):
File "main.py", line 1, in <module>
import units.py
ModuleNotFoundError: No module named 'units.py'; 'units' is not a packageOne 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.