0
0
Pythonprogramming~15 mins

__name__ and __main__ behavior in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
__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
1
Create the greet function and message variable
Create a function called greet that prints the variable message. Also, create a variable called message with the value 'Hello from the function!'.
Python
Need a hint?

Define message first, then define greet() that prints message.

2
Add the if __name__ == '__main__' block
Add the if __name__ == '__main__' statement below the function. Inside this block, print 'Script is being run directly'.
Python
Need a hint?

Use the exact line if __name__ == '__main__': and indent the print statement inside it.

3
Call the greet function inside the if __name__ == '__main__' block
Inside the if __name__ == '__main__' block, call the greet() function after the print statement.
Python
Need a hint?

Simply add greet() indented inside the if __name__ == '__main__' block after the print.

4
Print the output when running the script
Run the script and print the output. The output should show Script is being run directly followed by Hello from the function!.
Python
Need a hint?

Just run the script as is. The output should match exactly.