파이참으로 새로운 프로젝트를 만들고 나서 기본 파일 main.py에 선언되지 않은 __main__이라는 변수가 있었다.
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
파일명이 main.py였기 때문에 파일명이 들어가는 줄 알고 a.py라는 파일을 만들어봤다.
a.py에서는 if문이 False가 될 줄 알았지만 아니였다.
찾아보니 __name__ 변수는 파이썬에 기본적으로 내장된 변수이고, 다른 곳에서 해당 파일(__name__ 변수가 사용된 파일)을 import해서 사용할 대 모든 코드들이 실행되는 것을 방지하기 위해 사용된다고 한다.
import해서 사용하면 __name__에는 모듈(파일)의 이름이 들어가고, import가 아닌 해당 파일에서 실행할 경우 __main__이라는 값이 들어간다고 한다.
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__': # __name__ 변수는 파이썬에 이미 존재하는 내장변수이다.
# 이 파일을 다른 곳에서 import해서 사용하면 __name__에 파일의 이름 (여기서는 a)이 담긴다.
# 하지만 다른 곳이 아닌 여기서 실행하면 __name__에는 __main__이 담긴다.
# 다른 곳에서 이 파일을 import해서 사용할 때 모든 코드들이 실행되는 것을 방지하기 위해 사용된다.
print_hi('PyCharm')
a.py 파일