Your First Python Program
Launch Sprint · Day 4
Write your first Python program
You already installed Python and configured your IDE. Now it's time to create your first script, run it from the terminal, and understand what's happening under the hood.
2
Files created
Input · Output · Errors
Concepts
15 mins
Time
Create your script
- Inside a new folder (e.g.,
python-playground), create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
- Create
hello.pyand add:
from datetime import datetime
def greet(name: str) -> str:
timestamp = datetime.now().strftime("%H:%M:%S")
return f"👋 Hello {name}! It's {timestamp}."
if __name__ == "__main__":
user = input("What's your name? ")
print(greet(user))
Functions keep logic reusable; the `__name__ == "__main__"` guard prevents code from running on import.
- Run it:
python hello.py
Understand stdin/stdout
input()reads from standard input (terminal).print()writes to standard output.- Redirect output into files using
python hello.py > output.txt.
Add arguments
Upgrade to argparse so your script accepts flags:
import argparse
from datetime import datetime
parser = argparse.ArgumentParser(description="Greets a user.")
parser.add_argument("--name", default="Developer")
args = parser.parse_args()
now = datetime.now().strftime("%H:%M:%S")
print(f"Hi {args.name}, time is {now}")
Call with `python hello.py --name Ada`.
Debug it
Set breakpoints in your IDE or run:
python -m pdb hello.py
Commands:
| Command | Description |
|---|---|
n | Next line |
s | Step into function |
c | Continue execution |
p variable | Inspect value |
Common errors
| Error | Fix |
|---|---|
ModuleNotFoundError: No module named 'datetime' | Activate your virtual environment; ensure Python standard library is accessible. |
Permission denied on script | Remove BOM or ensure file is not marked read-only (Windows). |
| Output encoding issues | Use UTF-8 terminal or remove emoji from output. |
Next up in your learning path
Frequently Asked Questions
Where should I save my Python files?
Create a dedicated projects folder (e.g., `~/code/python/`). Each project should have its own virtual environment and `README`.
Why use a virtual environment?
Virtual environments isolate dependencies per project so packages never conflict and deployments remain reproducible.
Can I run Python scripts without the terminal?
Yes. Most IDEs let you run scripts with a click, but always learn the CLI to work comfortably on servers and CI pipelines.