Execute Python scripts in the terminal or an IDE. Python files have the .py extension. Whenever you make a Python script, save it as name.py

A simple program (hello.py) is shown below. The first line indicates that we want to use the Python interpreter. The 3rd line outputs a line of text “hello wlrd” to the screen.

The text below can be copied into a text editor and save as hello.py. Python works with files that end in .py.

#!/usr/bin/env python3

print('hello world')

You can use any text editor to create a Python program. I recommend using a text editor that supports syntax highlighting (text colouring) and line numbers.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Run Python

Run from terminal

You can start a Python program with the terminal or command line. This works on all platforms (Mac OS, Windows, Linux).

To open a terminal on Windows: press the windows key + r key (run program), type cmd or command and press enter.

On Mac OS use finder to start a terminal. You can hit command+space and type terminal, then hit enter.

Start program

To start the program, we have to open the command line and type:

python hello.py

For this to work you need to be in the correct directory. That means, the directory where your python program is located.

On Mac OS and Linux you can see the current directory with the command pwd.
If you use Windows the directory is shown in the command line title bra.

To change directory use the command ‘cd’ like this ‘cd /home/user/pythonprojects’ or ‘cd C:\Projects\’.

start python script

Run from IDE

To run a Python script from an IDE, start a project first. Once the project is created add your .py files (or create them in the IDE) and press run.

In the PyCharm IDE:

  • Start project
    • Welcome screen opens, click Create New Project.
    • On the main menu, choose File | New Project.
  • Select Python interpreter
    • Choose Python version from the list. Use 3.x
  • Click create
  • Add new Python file (File new) and add hello.py
  • Click the green triangle to start the program. Another option is to click right mouse button on your Python file and selecting run.

Other IDEs have a similar process to run a Python program (start project, add file, run button).

Output

You should see a line of text showing “hello world”.
python windows

Exercise

Try the exercises below:

  1. Make a Python program that prints your name.
  2. Make a program that displays the lyrics of a song.

After completing these continue with the next exercise.