FREE Courses
Text

Interactive Interpreter

Lesson 3

Python is a scripted language. This means that, instead of having to compile your code before it can be run, the Python interpreter runs each line of your code directly.

This allows you to use the Python interpreter interactively, simply by typing python at a command prompt. Try this now. You should get an output something like this:

Those three greater-than symbols (>>>) is what’s called the primary prompt and indicates that Python is in interactive mode and ready for you to input commands. Try these exercises by typing each command at the primary prompt and hitting enter:

1.  1+2
2.  4*5
3. 14/5
4. 14//5
5. 14%5
6.	x = "Hello"
7.	y = "There"
8.	print(x+y)
9.	print(x,y)
10.	print(x,y, sep="-")
11.	csv = "one,two,three"
12.	lst = csv.split(",")
13.	lst

How did you go? This is the output you should have seen in your terminal window:

So, let’s have a quick look at what we did here.

The first three commands should be easy to follow—you are just using Python as a calculator to perform simple addition, multiplication and division. But what about examples 4 and 5?

In example 4 we are performing what is called integer division, so 14//5 is returning the result of 14 divided by 5 without the remainder. And how would you find out the remainder? Use the modulo operator (%)—which is exactly what we are doing in example 5. So 14%5 returns the remainder after dividing 14 by 5.

In examples 6 to 10, things are getting a bit more interesting. In examples 6 and 7, we are simply assigning a string to two new variables. If you have ever used another programming language, you will notice that neither of these variables must be declared before assigning a value to the variable. Python shortcuts this extra cruft by creating a variable when you assign something to it.

You will also notice in examples 6 and 7 I didn’t have to declare the new variables as strings. This is because Python is dynamically typed, meaning that Python assumes the type of a variable by what you assign to it. In this case, Python assumes that x and y are strings because you assigned strings to them.

Now that we have assigned the strings “Hello” and “There” to variables x and y respectively, we are employing one of Python’s most useful functions—print()—to print some results out to the terminal. In example 8 we are using the + operator to concatenate—or join—the two strings.

In example 9, we are using the comma (,) to separate x and y; which is basically saying “print x and a space and then print y”. The space is the default separator when printing variables. Like most things in Python, this default behavior can be overridden, which is what we are doing in example 10—overriding the space with sep=”-” and now the variables print out with a dash (-) instead of a space separating them.

The last two examples demonstrate how Python can tackle more complex problems in a simple and intuitive way. The string csv might be a single line from a comma-delimited spreadsheet file that you need to import into Python. The string class in Python has many methods built in to allow you to manipulate strings.

One of those methods is split()split() allows you to split a string into a Python list using the string you pass to split() as a delimiter. In this case, we are using a comma (,) as the delimiter which splits our string “one,two,three” at the commas, producing a list of three items (['one', 'two', 'three']).

Testing Code With the Interactive Interpreter

The examples so far have been simple, but the takeaway is that anything that runs in Python will run from the interactive interpreter. This is supremely useful for working out how to write code to solve a problem or produce the output you want.

This simple, iterative way that you can work with Python makes the development process much quicker and far less painful that the write-compile-test-rewrite cycle of other programming languages.

You can test code with the interactive interpreter by simply cutting and pasting the code from your editor into the terminal window, or you can type the code in at the primary prompt. It’s important to understand, however, how Python interprets more complex code. For example, type this at the primary prompt:

for i in range(5):

This is the start of a for loop (more on for loops a bit later). For the sake of this example, I am using the for loop to demonstrate what Python does with this command.

Notice, when you hit Enter, that Python dropped to the next line and instead of the command prompt (>>>), there is now an ellipsis (...). This is because Python is waiting for more input from you.

The ellipsis is referred to as Python’s secondary prompt.

This is where most beginners trip up, remember: white-space matters. So if you just start typing at the secondary prompt this is what happens:

>>> for i in range(5):
... print(i)
File "<stdin>", line 2 print(i)
^
IndentationError: expected an indented block
>>>

The interactive interpreter doesn’t automatically indent your code—you must add the indentation yourself. You can do this by either adding four spaces, or hitting the tab key, like so:

>>> for i in range(5):
...     print(i)

You may need to hit Enter once more to tell Python that you have finished entering code and the loop will run:

>>> for i in range(5):
...     print(i)
... 
0
1
2
3
4
>>>

Very cool. To exit the interactive interpreter, you can either type exit() at the Python prompt or type CTRL-Z on your keyboard and hit Enter, which will take you back to your standard system command prompt.

Here’s a screenshot of the complete exercise:

Using the Interactive Interpreter with Django

Using the standard Python interactive interpreter is great for testing general Python code, but if you try to run any Django code from the Python prompt, you will get the error "No module named 'django'."

This is because Python has no knowledge of Django when you install it in a virtual environment and because your Django project requires a few files loaded (particularly settings.py) to be able to run.

Fortunately, Django’s developers thought of this and provided a convenient management function that allows you to use the Python interpreter with Django. First, start up your virtual environment. Then, change into your mfdw_site directory (type cd mfdw_site at the command prompt) and run the command python manage.py shell:

This looks just the same as a Python prompt, but now you can access everything within your Django project. For example, your Project settings:

If you want to see all the settings, type in:

>>> dir(settings)	# Be warned, it's a long list!

There’s not a lot more we can play with right now as your project is only an empty shell, but we will be revisiting the Django/Python interactive interpreter a few times in the course, so you will have plenty of chances to test it out.

Pen