Why doesn't my code in "test.py" display anything when I "import test"?

Question:

I have this code in a file called test.py:

person = {'name': 'Jemm', 'age': '23'}
sentence = 'My name is ' + person['name'] + 'and i am' + person['age'] + 'years old.'

print(sentence)

When I try import test, I don’t get any output. Why?

Asked By: Imtango30

||

Answers:

I guess the problem is that you didn’t save the file after you did all the code in test.py, what happens if save it then run import test somewhere else, that’s what i think

Also as Messa said, “There is a test module in Python itself. Be sure you are running your module. You must be in the same directory as your file test.py to import your file instead of the Python one.” that’s also useful information, have to be same directory as test.py (your file)

If you’re not in the same directory, do:

__import__('whole filepath')

For it.

Answered By: U12-Forward
>>> import test
>>> print(test)
<module 'test' from '/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/test/__init__.py'>

There is a test module in Python itself. Be sure you are running your module. You must be in the same directory as your file test.py to import your file instead of the Python one.

Update: Python uses a search path list mechanism for finding modules when importing. The “current working directory” is usually at the first place in this list (the empty string). See PYTHONPATH and sys.path.

You can add your own path(s) into PYTHONPATH (in shell/command line) or sys.path (in Python).

Answered By: Messa
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.