ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
Modules and imports
Your programs are getting long, and some functions, like a VAT calculation, are useful
in more than one of them. By the end of this lesson you'll split a program into files,
import your own functions from another file, and finally understand the
if __name__ == "__main__": line from lesson 5.8.
A file other files can use
Any Python file is a
:
a file whose functions other files can use. This runner has two files. Look at
money.py in its tab, then run main.py:
main.py
import money
print(money.vat(200))
print(money.santim_to_birr(250))In the editor, press Escape then Tab to move on.
money.py
def vat(price):
return price * 15 // 100
def santim_to_birr(santim):
return santim / 100In the editor, press Escape then Tab to move on.
money finds money.py (the module's name is the file's name without .py), runs it,
and gives you the name money. You reach its functions with a dot, money.vat, just
like random.randint in lesson 3.5. Change 15 to 10 in the money.py tab and run
again: the first line becomes 20.
There are three ways to write an import:
main.py
import money
from money import vat
import money as m
print(money.vat(200))
print(vat(200))
print(m.vat(200))In the editor, press Escape then Tab to move on.
money.py
def vat(price):
return price * 15 // 100
def santim_to_birr(santim):
return santim / 100In the editor, press Escape then Tab to move on.
import money keeps every name behind money., so you can always see where a function
came from. from money import vat brings in just vat, to use without the dot. as
gives a module a shorter name, as in import statistics as stats; use it for long
names.
An import runs the file, once
Importing a module runs its whole file, top to bottom. This money.py has a print at
the top, and main.py imports it twice. Predict:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
import money
import money
print(money.vat(200))Also in the folder with main.py:
money.py
print("Loading money")
def vat(price):
return price * 15 // 100Python prints
Loading money 30
The first import runs money.py, which prints. Python remembers modules it has already loaded, so the second import does nothing.
If you picked the first answer, you thought import only collects the functions; it
runs the file, print and all. If you picked the last, you thought each import runs
it again. Python runs a module the first time it's imported and remembers it for the
rest of the run, so the second import money just gives you the same module. Run the
program again and it starts fresh: Loading money prints again, once.
if __name__ == "__main__":
Every module gets a name __name__. Here money.py prints its own __name__. First,
main.py imports it. Predict:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
import moneyAlso in the folder with main.py:
money.py
print("money.py sees", __name__)Python prints
money.py sees money
An imported module's __name__ is its own module name: money. Only the file you run gets __main__.
Now run money.py itself, with python money.py. Predict again:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
print("money.py sees", __name__)Command
python money.py
Python prints
money.py sees __main__
The file Python starts from gets the name __main__, whatever the file is called.
The file you run gets __name__ set to "__main__"; a file that's imported gets its
module name, "money". That's what lesson 5.8 promised: if __name__ == "__main__":
means "only when this file is the one being run". Code under it runs when you run the
file, and not when another file imports it. Here, money.py checks itself:
main.py
from money import vat
print(vat(300))In the editor, press Escape then Tab to move on.
money.py
def vat(price):
return price * 15 // 100
if __name__ == "__main__":
print("Checking vat:", vat(200) == 30)In the editor, press Escape then Tab to move on.
The check doesn't print, because money.py was imported. In a terminal,
python money.py would print Checking vat: True. That's why main() goes under that
line: other files can import your functions without starting your whole program.
ጥያቄ
Inside money.py, what is __name__ when main.py does import money?
Names that clash
Python looks for a module in the folder of the file you ran first, before the
standard library's files. (Only the few modules built into Python itself, like sys,
are found before that.) So a file of yours named like a standard module takes its
place:
One more kind of clash: from math import * brings in every name from math, and they
replace yours without a word:
e = "Elias"
from math import *
print(e)In the editor, press Escape then Tab to move on.
math has a name e (a number), and it replaced Elias. With import math you'd write
math.e, and your e would be safe. Avoid import *.
መልመጃ
Move the grade functions
grades.py already has the grade functions from lesson 5.8. main.py still has its
own copies. Delete the copies from main.py and import grade_for and
grade_points from grades instead. The program should print the same thing.
Score (0-100): 85
Grade: A (4.0 points)Your code
main.py
def grade_for(score):
if score >= 85:
return "A"
elif score >= 70:
return "B"
elif score >= 50:
return "C"
else:
return "F"
def grade_points(letter):
points = {"A": 4.0, "B": 3.0, "C": 2.0, "F": 0.0}
return points[letter]
def main():
score = int(input("Score (0-100): "))
grade = grade_for(score)
print(f"Grade: {grade} ({grade_points(grade)} points)")
if __name__ == "__main__":
main()In the editor, press Escape then Tab to move on.
grades.py
def grade_for(score):
if score >= 85:
return "A"
elif score >= 70:
return "B"
elif score >= 50:
return "C"
else:
return "F"
def grade_points(letter):
points = {"A": 4.0, "B": 3.0, "C": 2.0, "F": 0.0}
return points[letter]In the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
from grades import grade_for, grade_points
def main():
score = int(input("Score (0-100): "))
grade = grade_for(score)
print(f"Grade: {grade} ({grade_points(grade)} points)")
if __name__ == "__main__":
main()ዋና ዋና ነጥቦች
- A module is a Python file other files can use;
import moneyloadsmoney.py. import money(thenmoney.vat) orfrom money import vat; avoidimport *.- Importing runs the module's file once per program, however many times you import it.
__name__is"__main__"in the file you run and the module's name when it's imported; code underif __name__ == "__main__":runs only when the file is run.- Python looks in your own folder first: never name a file
random.pyorjson.py.