Wednesday, August 24, 2022

[FIXED] why does the code print the "test message" although I wrote just the code for printing the attribute "a"

Issue

I don't know why it prints both "test message" and "ABC" instead of just "ABC". I think just wrote the code for printing the attribute "a" but it prints something more!

I have two modules: "first.py" & "second.py"

first.py is:

import second
print(second.a)

second.py is:

a="ABC"
print("test message")

OUTPUT is:

test message
ABC

Solution

import second will run all code in second.py. print("test message") is also executed. If you want to prevent this use below

a = 'ABC'
if __name__ == "__main__":
    print("test message")

if __name__ == "__main__": will only run when run from that file.



Answered By - Desty
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.