__name__ == '__main__'
- Python course
- Beginner
- Lesson 109/116
- 5 min
Learn module/run distinction with __name__ == '__main__'.
__name__ == '__main__'
Every Python file has a hidden __name__ variable. When the file is run directly, __name__ is '__main__'. When imported from another file, __name__ becomes the file name:
# script.py
if __name__ == '__main__':
print("doğrudan çalıştı")This pattern makes code run only when the file is executed directly. When imported, this block is skipped.
This is standard for test code and command-line entry points.
Why it is used
This pattern is used in two common situations. First, letting a module work both as a library and as a script. Second, embedding test code in the module:
def topla(a, b):
return a + b
if __name__ == '__main__':
print(topla(2, 3)) # 5Here topla can be imported; the test print only appears on direct execution. This makes modules flexible.
It is a common pattern in Python projects.
Practice Write the __name__ == '__main__' block
Write if __name__ == '__main__':. Inside the block write print("çalıştı").
Starter code
# write the __name__ condition
# print a message inside the blockSample solution
if __name__ == '__main__':
print("çalıştı")Expected output
çalıştı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the purpose of the __name__ == '__main__' block?
- Prevent module import
- Define a class
- Run code only on direct execution Correct answer
- Define a variable
Explanation: This block runs only when the file is executed directly.
2 Match __name__
| Term | Meaning |
|---|---|
__name__ |
Hidden variable |
'__main__' |
Direct execution |
if __name__ |
Condition |
import |
Skipped block |
3 Complete the __name__ variable
if ____ == '__main__':
print('çalıştı')
if __name__ == '__main__':
print('çalıştı')
Explanation: The __name__ variable becomes '__main__' on direct execution.