0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Imtango30
  • 143
  • 1
  • 2
  • 9

2 Answers2

3
>>> 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).

Messa
  • 24,321
  • 6
  • 68
  • 92
0

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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114