Home > Net >  why does the code print the "test message" although I wrote just the code for printing the
why does the code print the "test message" although I wrote just the code for printing the

Time:04-15

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

CodePudding user response:

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.

  • Related