PythonYour First Program

Your First Program

Every Python journey starts the same way: a text file, a few words of code, and a terminal command that brings it to life. In this lesson you will write a real "Hello, World!" program, run it from the command line, and then go a level deeper into two ideas that separate beginner scripts from properly structured Python programs: the if __name__ == "__main__": idiom and the shebang line that turns a script into a standalone executable.

Writing hello.py

Open your editor of choice — VS Code, PyCharm, even a plain text editor — and create a new file named exactly hello.py. The .py extension is what tells your editor (and Python tooling) that this is Python source code.

Python
print("Hello, World!")

That single line calls Python's built-in print() function with the string "Hello, World!". Save the file, then open a terminal in the same folder.

Warning
Save the file with a lowercase .py extension, not .txt, .py.txt, or .PY. Some editors on Windows silently append .txt when you save a new file for the first time — if python hello.py reports that the file cannot be found, check the actual filename in a file explorer with extensions visible.
Running it from the terminal

With the file saved, run it using the python interpreter. Depending on your operating system and how Python was installed, the command is either python or python3.

Bash
python hello.py
# or, on macOS/Linux where "python" may point to Python 2 or not exist at all
python3 hello.py
Hello, World!

That's it — you've written and executed a Python program. Behind the scenes, the python command started the interpreter, loaded hello.py, executed each line from top to bottom, and exited once it reached the end of the file.

Tip
If python --version reports Python 2.x, use python3 and pip3 instead throughout this tutorial series. Python 2 reached end-of-life in 2020, and every example here targets Python 3.
The __name__ variable

As your programs grow, you'll often want a file to work two ways at once: as a standalone script you run directly, and as a module that other files import. Python gives every module a special built-in variable called __name__ that lets your code tell the difference.

Here's the rule: when you run a file directly with python somefile.py, Python sets that file's __name__ variable to the string "__main__". But when the same file is imported by another module, __name__ is set to the module's actual name (i.e. the filename without the .py extension).

Python
# greetings.py
def greet(name):
    return f"Hello, {name}!"

print(f"greetings.py has __name__ = {__name__}")

if __name__ == "__main__":
    # This block only runs when greetings.py is executed directly.
    user_name = input("What's your name? ")
    print(greet(user_name))

Run this file directly and __name__ equals "__main__", so the code inside the if block executes:

Bash
python greetings.py
greetings.py has __name__ = __main__
What's your name? Ada
Hello, Ada!

Now create a second file in the same folder that imports greetings instead of running it:

Python
# app.py
import greetings

print(greetings.greet("Grace"))

Bash
python app.py
greetings.py has __name__ = greetings
Hello, Grace!

Notice two things. First, the top-level print() statement in greetings.py still runs when it's imported — anything outside the if block executes as soon as the module is loaded, whether that's via a direct run or an import. Second, __name__ is now "greetings" (the module name), not "__main__", so the input() prompt never fires and app.py never gets asked for a name interactively.

This is exactly the behavior you want: importing greetings to reuse its greet() function shouldn't also trigger an interactive prompt meant only for when the file is run as a script.

Why the idiom matters

The if __name__ == "__main__": idiom is Python's way of saying "only run this code when this file is the entry point of the program, not when it's being borrowed for its functions and classes." It shows up constantly in real codebases for a few concrete reasons:

  • It lets a single file serve double duty as both a reusable module and a runnable script, without one use case interfering with the other.

  • It keeps side effects — printing, reading input, hitting a network, writing files — out of the way of anyone who just wants to import your functions.

  • It makes automated testing easier: test files can import functions from your script and call them directly without accidentally executing the whole program.

  • It matches a convention every experienced Python developer recognizes on sight, making your code easier for others to read.

A common pattern is to wrap the "script" behavior in a small main() function and call that from the guard, which keeps the module-level namespace tidy:

Python
def main():
    print("Hello, World!")


if __name__ == "__main__":
    main()
Note
You will see if __name__ == "__main__": at the bottom of almost every substantial Python script and module in the wild, including in the standard library. Get comfortable writing it now — it becomes automatic.
Shebang lines and executable scripts

So far you've run scripts by typing python hello.py. On macOS and Linux (and on Windows under WSL), you can skip typing python every time by adding a shebang line as the very first line of the file and marking the file as executable.

A shebang tells the operating system's shell which interpreter should run the file. The most portable form uses env to locate whichever python3 is first on your PATH, rather than hardcoding an absolute path that might not exist on every machine:

Python
#!/usr/bin/env python3
"""A tiny script you can run directly once it's executable."""

def main():
    print("Hello, World!")


if __name__ == "__main__":
    main()

Save this as script.py, then make it executable with chmod +x, which grants the file execute permission:

Bash
chmod +x script.py
./script.py
Hello, World!

Once the file is executable, ./script.py runs it directly — the shell reads the shebang line, sees /usr/bin/env python3, and hands the rest of the file to that interpreter automatically. You no longer need to type python3 yourself.

Warning
The shebang line only works if the file has execute permission and you run it with a path (like ./script.py or an absolute path). Forgetting chmod +x is the most common reason ./script.py fails with a "permission denied" error. Windows ignores shebang lines entirely outside of WSL — there, python script.py is still the way to go.
A quick look ahead: command-line arguments

Real scripts often need input from outside — a filename, a flag, a config value — supplied right on the command line, e.g. python greet.py Ada. Python exposes whatever follows the script name as a list of strings in sys.argv, where sys.argv[0] is the script's own path and sys.argv[1] onward are the arguments you typed:

Python
import sys

if __name__ == "__main__":
    print(sys.argv)

Bash
python argv_demo.py Ada 42
['argv_demo.py', 'Ada', '42']

That's the whole mechanism in a nutshell. Parsing those arguments robustly — handling flags like --verbose, optional values, help text, and validation — is its own topic and deserves a dedicated page built around Python's argparse module. For now, just know that sys.argv is where command-line input arrives.

Tip
Keep this page's three building blocks in mind as you move on: a plain script run with python file.py, the if __name__ == "__main__": guard for dual-purpose files, and the shebang line for turning a script into its own executable command. Together they form the backbone of nearly every Python program you'll write.