How to import a Python script as a module?

QuestionsQuestions8 SkillsProDec, 18 2025
0107

To import a Python script as a module, you use the import statement followed by the filename (without the .py extension).

In the context of your current lab, here is how you would do it:

1. Basic Import

If you are in the same directory (~/project) and you want to use the functions from number_analyzer.py in a new script:

import number_analyzer

# Now you can call the function using the module name
number_analyzer.analyze_numbers()

2. Import Specific Functions

If you only want that specific function and don't want to type the module name every time:

from number_analyzer import analyze_numbers

# Now you can call it directly
analyze_numbers()

Important Details:

  • Filename Rules: To be imported easily, your filename should start with a letter and contain only letters, numbers, or underscores (e.g., number_analyzer.py is fine, but 123-analyzer.py would cause issues).
  • The if __name__ == "__main__": block: Because you included this block in your script, when you import number_analyzer, the program will not immediately start asking you for "Enter a number". It will simply load the function definition, waiting for you to call it.

Try it in the VM:

  1. Create a second file: touch ~/project/test_import.py
  2. Open it and write:
    from number_analyzer import analyze_numbers
    print("Import successful! Starting the analyzer...")
    analyze_numbers()
  3. Run it: python3 ~/project/test_import.py

This demonstrates the power of modular programming in Python! Do you want to try creating a separate module now?

0 Comments

no data
Be the first to share your comment!