Once in the Python prompt, we can start typing code, and it will get executed.

Let’s start with a simple hello world:

>>>"hello world"

'hello world'

In interactive mode, it is not necessary to use the print() function – every expression is executed and returns its result.

Throughout this documentation, code examples with lines starting in >>> are intended as interactive sessions in Terminal. All other examples are scripts.

The same is valid to mathematical expressions (or for any Python expression):

>>>1+1

2

>>>'x'in'abcdef'

False

It’s also possible to write multi-line code in interactive mode. Notice how the prompt changes to indicate that the interpreter is waiting for input:

>>>foriinrange(4):...i...

0
1
2
3

User input

Interactive mode allows us to prompt the user for input while we are running a programming session. This can be done using the built-in function input(), which returns the string that was entered by the user.

>>>answer=input('What… is your quest?')

Running existing scripts

The interactive mode is useful for writing quick tests and short scripts, but it is not really suitable for working with larger pieces of code. In that case, it makes more sense to write scripts as separate .py files, and use Terminal only to run execute them.

As an example, let’s suppose we have a Python script which prints helloworld as output:

print('hello world')

This script is saved in the desktop as hello.py.

To execute this file in Terminal we use the command python followed by the path to the script file:

username:~ username$ python /Users/username/Desktop/hello.py

Instead of typing out the full path, you can also drag the file from Finder to the Terminal prompt to get its path.