0
# file1.py
a = 1
print(a)
# 1
# file2.py
from file1 import a
print(a)
# 0

I want "1" output in file2.py, why it doesn't work?

8
  • 3
    Are the 2 files in the same directory? Commented Jul 18, 2020 at 11:54
  • @bigbounty If it was in a different directory, error would be ModuleNotFoundError: No module named 'file1' Commented Jul 18, 2020 at 11:56
  • @RoshinRaphel OP didn't specify any errors Commented Jul 18, 2020 at 11:57
  • @bigbounty Yes that is true, my bad, I assumed that by #0 he meant the output was 0 Commented Jul 18, 2020 at 11:58
  • I dont have any errors, in same directory Commented Jul 18, 2020 at 12:02

1 Answer 1

1

Your code should give the below output

1

1

You get two 1's in the output because when python imports a file it executes it. When file1 is imported, it's print statement is executed. The second 1 is from the print statement in the file2

If you are getting 0 as output check if you have the permissions to execute these files (Since your files are in root directory)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.