Thuta Learning
Python
BasicProgrammingBeginner

Python Get Started

PythonLesson 325 min

What you'll walk away with

  • Install Python on Windows, macOS or Linux and check its version
  • Choose between the interactive REPL (>>>) and running a script file
  • Create and activate a virtual environment with python -m venv
  • Explain why python -m pip is safer than a bare pip command
  • Know what the if __name__ == "__main__": guard is for

Explain it simply

Explain it simply

To run Python code, your computer needs a program called the Python interpreter. Think of it as a translator: it reads the code you wrote and makes the computer carry it out. Once Python is installed, typing python in a terminal calls that translator.

There are two ways to talk to the interpreter. In the REPL (the >>> prompt) you type one line and get the answer immediately, which is perfect for experiments. Writing code in a .py file and running it is for real programs you want to save and run again.

Problem → Why → Solution

The problem: a package you just installed is missing

You run pip install requests and see "Successfully installed". Then your script fails with ModuleNotFoundError. The computer has two Pythons, say 3.12 and 3.13; pip installed into one of them while python runs the other. This is the most common setup problem beginners hit.

terminal
$ pip install requests
Successfully installed requests-2.32.3
$ python app.py
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'

Why does this happen?

pip and python are two separate commands, and depending on your PATH they can point at different Python installations. Writing python -m pip install requests says "the pip that belongs to this python", so the place you install into is always the place you run from. Giving every project its own virtual environment makes the problem rarer still.

Core concept: interpreter, environment and entry point

On Windows, download the installer from python.org and tick "Add python.exe to PATH" on its first screen. Windows also gets the py launcher, so py --version works too. On macOS and Linux the command is usually python3, so check with python3 --version. After installing, close and reopen the terminal; an old window does not see the new PATH.

PlatformHow to installCheck command
WindowsRun the python.org installer and tick "Add python.exe to PATH"python --version or py --version
macOSUse the python.org installer (Homebrew users: brew install python)python3 --version
LinuxMost distributions ship Python 3; otherwise install it with the package managerpython3 --version

Typing python on its own opens the REPL with a >>> prompt. Enter 2 + 3 and it shows 5 at once; leave with exit() or Ctrl+D (Ctrl+Z then Enter on Windows). Typing python hello.py instead runs the file from start to finish and then exits. The REPL echoes the value of each expression automatically, but inside a file nothing appears unless you call print().

terminal
python --version    # which interpreter? (python3 on macOS/Linux)
python              # open the REPL; leave it with exit()
python hello.py     # run a file from start to finish

A virtual environment (venv) is a small private copy of Python inside your project folder, with its own set of installed packages. Project A can use Django 4 while project B uses Django 5 and neither disturbs the other. Create one with python -m venv .venv; once activated, both python and pip in that terminal point inside .venv.

The last piece is the entry point. When you run a file directly, Python sets a special variable, __name__, to "__main__"; when another file imports it, __name__ is the module's name instead. Calling main() under if __name__ == "__main__": means the file does its work when run, but stays quiet when imported.

What does -m mean?

python -m name means "find the module called name in this interpreter's library and run it as a program". python -m venv, python -m pip and python -m http.server all work this way. Because the module is looked up by that exact python, it no longer matters which pip happens to be first on your PATH.

Mental model: one project, one environment
  1. Create a project folder
  2. python -m venv .venv
  3. Activate .venv
  4. python -m pip install ...
  5. Run python main.py

As long as you install and run through the same interpreter, most ModuleNotFoundError surprises disappear.

General pattern: a script's entry point

python
def main():
    # the program's work goes here
    ...

if __name__ == "__main__":
    main()

Put the work inside a main() function and call it only when the file is run directly. The ... (Ellipsis) is a placeholder meaning "code goes here".

Example: running your first script

Save this as hello.py and run python hello.py (python3 hello.py on macOS and Linux). The second line reports the version of the interpreter that is actually running: on Python 3.13 you get the output below, and on another version the numbers change. Printing the full sys.version string would add build details that differ on every machine, so the code prints only major.minor.

hello.py
import sys


def main():
    print("Hello, World!")
    major, minor = sys.version_info[:2]
    print(f"Python {major}.{minor} is running this file")
    print("Welcome to Python!")
    print("Let's start coding!")


if __name__ == "__main__":
    main()

Code breakdown

  1. Line 1import sys

    sys is a standard library module, so nothing needs installing. It holds information about the running interpreter.

  2. Line 4def main():

    The program's work is grouped in a function called main. The indented lines below it are the function body.

  3. Line 6major, minor = sys.version_info[:2]

    sys.version_info is a group of numbers such as (3, 13, ...). [:2] takes the first two, and they are unpacked into major and minor in one step.

  4. Line 12if __name__ == "__main__":

    Run with python hello.py, __name__ is "__main__", so main() is called. If another file does import hello, __name__ is "hello" and nothing is printed.

You should see
Hello, World!
Python 3.13 is running this file
Welcome to Python!
Let's start coding!

Setting up a virtual environment step by step

1. Create and enter a project folder

Run mkdir weather-app and then cd weather-app. Every following command runs from inside this folder.

2. Create the environment

python -m venv .venv creates a .venv folder containing its own Python and pip.

3. Activate it

In Windows PowerShell run .venv\Scripts\Activate.ps1, in cmd run .venv\Scripts\activate.bat, and on macOS or Linux run source .venv/bin/activate. When (.venv) appears before the prompt, it worked.

4. Install packages and record them

Run python -m pip install requests, then python -m pip freeze > requirements.txt to save the exact versions. Type deactivate when you are done.

terminal (macOS / Linux)
mkdir weather-app && cd weather-app
python3 -m venv .venv
source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txt
python main.py
deactivate

In real projects

Where this shows up in real projects

When a developer clones a company project, the first commands are exactly this lesson: python -m venv .venv, activate it, then python -m pip install -r requirements.txt. Because requirements.txt pins the package versions, everyone on the team and the production server get the same dependencies. The .venv folder itself goes into .gitignore and never into git, since each machine can rebuild it.

Editors such as VS Code and PyCharm ask you to select the project's .venv as the interpreter, so autocomplete and error checking can see the installed packages. If the editor says "Import could not be resolved" while the code runs fine in the terminal, the editor has picked a different interpreter. In data science, Jupyter Notebook plays the role of a richer REPL.

Common mistakes

Common mistakes

1. Forgetting the PATH checkbox on Windows

Without it, typing python gives a "not recognized" error or opens the Microsoft Store. If py --version works, Python is installed; rerun the installer, choose Modify, and add it to PATH.

2. Typing shell commands into the REPL

Entering pip install requests or python hello.py at the >>> prompt gives a SyntaxError, because those are terminal commands, not Python code. Leave the REPL with exit() first, then type them.

3. Installing everything into the global Python

When every project installs into the global Python, upgrading a package for one project can break another, and you end up with code that only works on your machine. Give each project its own .venv.

Best practices

Best practices

  • Always name the environment folder .venv; most editors detect it automatically.
  • Update requirements.txt every time you install a new package.
  • Make python -m pip, not bare pip, a habit for every install.
  • Avoid spaces in project folder and file names; terminal commands are easier to type without them.

Mini challenge

Mini challenge: an environment check script

Write env_check.py, a script that reports whether your setup is ready: the version, whether it runs inside a virtual environment, and whether the version is new enough.

  • Do all the work in main() and call it behind the __name__ guard
  • Print major.minor from sys.version_info
  • Detect a virtual environment with sys.prefix != sys.base_prefix
  • Warn the user to upgrade if the version is older than (3, 10)
env_check.py
import sys


def main():
    # TODO: print "Python X.Y"
    # TODO: in_venv = compare sys.prefix with sys.base_prefix
    # TODO: print whether we are inside a virtual environment
    # TODO: if sys.version_info is older than (3, 10), print an upgrade warning,
    #       otherwise print that the version is fine
    ...


# TODO: call main() only when this file is run directly

Expected: Run with Python 3.13 inside a venv: Python 3.13 Inside a virtual environment: True Version OK for this course. (Outside a venv the second line shows False.)

Show hint

Tuples compare directly, item by item: sys.version_info < (3, 10) checks the major number first, then the minor.

Show solution
env_check.py
import sys


def main():
    print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
    in_venv = sys.prefix != sys.base_prefix
    print(f"Inside a virtual environment: {in_venv}")
    if sys.version_info < (3, 10):
        print("Please upgrade to Python 3.10 or newer.")
    else:
        print("Version OK for this course.")


if __name__ == "__main__":
    main()

Quick quiz 1 / 3

pip install pandas succeeded, yet python app.py raises ModuleNotFoundError. What is the most likely cause?

Quick quiz 2 / 3

tools.py ends with if __name__ == "__main__": main(). What happens when another file runs import tools?

Quick quiz 3 / 3

Typing 2 + 3 in the REPL shows 5. What does running a file calc.py that contains only 2 + 3 print?

What to remember

  • Always check which Python runs with python --version (python3 on macOS/Linux; py also works on Windows).
  • The REPL is for experiments and .py files are for saved programs; a file shows nothing without print().
  • Give each project its own python -m venv .venv and install with python -m pip.
  • if __name__ == "__main__": makes a file act when run but stay quiet when imported.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Get Started | Thuta Learning