__name__ and __main__ behavior
📖 Scenario: Imagine you are creating a Python script that can be used both as a program and as a module imported by other scripts. You want to control what code runs only when the script is executed directly.
🎯 Goal: Build a Python script that defines a function and uses the if __name__ == '__main__' check to run code only when the script is run directly, not when imported.
📋 What You'll Learn
Create a function called
greet that prints a greeting message.Create a variable called
message with the value 'Hello from the function!'.Use the
if __name__ == '__main__' statement to call the greet function only when the script is run directly.Print
'Script is being run directly' inside the if __name__ == '__main__' block.💡 Why This Matters
🌍 Real World
Many Python scripts are written to be both reusable modules and standalone programs. Using <code>if __name__ == '__main__'</code> helps control code execution depending on how the script is used.
💼 Career
Understanding this concept is essential for writing clean, reusable Python code in software development, automation scripts, and data science projects.
Progress0 / 4 steps