Loading...

Python if __name__

You already have two questions that write one line. You want those questions to run only when you start this file yourself. The file is box.py. You will start box.py, type mug, then 4, and the last line will be mug 4.

questions run only when you start box.py

python
def label(item, count):
    return f"{item} {count}"

if __name__ == "__main__":
    item = input("item: ")
    count = input("how many: ")
    print(label(item, count))

You start box.py. The screen waits at item: and you type mug, then press Enter. It waits at how many: and you type 4, then press Enter. The last line is mug 4. Those lines ran because you started this file. The name __name__ holds __main__. The if line sees that the two match, so the questions run. The program is done. There is no fourth line.

a different file only writes shelf

python
import box
print("shelf")

This second program is a different file, shelf.py. You start shelf.py, and you do not type mug or 4. The screen shows one line, shelf. shelf.py opens box.py with import, so inside box.py the name __name__ holds box. That is not __main__, so the questions do not run. item: does not appear, and mug 4 is not written. The skipped questions do not write None. print writes shelf because that line is in the file you started.

You can keep the two questions from running unless you start box.py yourself. Start box.py, type mug, then 4, and the last line is mug 4. Start shelf.py and the screen is only shelf. The next page hands you one value, then the next.

The questions run only when you start the file

Start box.py, type mug, then 4. The last line is mug 4. Start shelf.py and the screen is shelf. The next page hands you one value, then the next.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top