Python for Django Developers: Part 1


If you understand the basics of Python, you will be able to understand Django in a much more comprehensive way. For example, by having a greater understanding of Python, you will be able to identify the bits of Django that are plain Python and the bits that are unique to Django.

This course is only meant to be a very basic introduction to Python so you can better understand how Django works. It’s not meant to be a complete tutorial on Python – that would require an entire book on its own!

To get full benefit out of Django, I highly recommend you expand your knowledge of Python as soon as possible. In each lesson, I have included links to Django and Python documentation where you can find extra information about each Python topic.

Code Layout – Readability Counts

One of the founding principles behind Python’s design is that code is read much more often than it’s written. Once a piece of code is written, it often passes through many hands—other developers, documentation authors, auditors and testers. Experienced programmers will also tell you that being able to understand your own code many months, or even years, after you wrote it is extremely important. Under this guiding principle, Python was designed to mimic natural written English as much as possible. One of these design choices was to use white-space as a delimiter, rather than braces ({}), or the BEGIN\END type statements used by other languages. A delimiter is something that defines the beginning or the end of a block of related text. Consider the following:

# Kate's Awesome Nachos

1.	Collect Ingredients:
    a.	Large bag of corn chips
    b.	Can of refried beans (preferably chili)
    c.	Jar of salsa (not hot!)
    d.	Grated cheese
    e.	Guacamole
2.	Prepare Nachos:
    a.	Tip bag of corn chips in oven dish
    b.	Spread refried beans over corn chips
    c.	Pour on jar of salsa
    d.	Top with cheese
3.	Cook in oven for 20 mins
4.	Serve with guacamole

We can easily understand each step of this simple (but delicious!) recipe because it’s formatted in a way that all English speakers can understand— relevant information is grouped together in sentences and paragraphs and indentation is used so we can differentiate between Step 1, collecting the ingredients and Step 2, preparation of the nachos.

Python treats whitespace the same way, for example the ingredients written as a Python list may look like:

ingredients = [ 
    "corn chips", 
    "refried beans", 
    "grated cheese", 

You will notice that Python lists use brackets ([]) as a delimiter, with the indentation and surrounding whitespace clearly differentiating where the list starts and ends. (More on lists shortly.) Functions for preparing and cooking the nachos might be written like this:

def prepare_nachos(ingredients): nachos = ""
    for ingredient in ingredients[:4]: 

def cook_nachos(nachos):
# cook in oven for 20mins

Now this is a rather silly example, but I bet that you found it easy to follow—even without quite understanding Python syntax. Our list of ingredients is broken up into one ingredient per line to create our ingredients list, and we have used indentation to differentiate between the two Python functions (prepare_nachos and cook_nachos) and the code that belongs to each function. Here are some real examples that you will see later in the course:

# A list from the file: 


# A function from

def index(request, pagename): 
    pagename = '/' + pagename
    pg = Page.objects.get(permalink=pagename) 
    context = {
        'title': pg.title, 
        'content': pg.bodytext,
        'last_updated': pg.update_date, 
        'page_list': Page.objects.all(),
    return render(request, 'pages/page.html', context)

I don’t expect you to understand this code right now, but as you can see, the layout of the code makes it easy to follow without you necessarily understanding exactly what’s going on.

Indentation and intuitive use of whitespace are not the only stylistic conventions designed to make Python code more readable. Python has a complete style guide called PEP8. I strongly encourage you to read this document, absorb what it has to say any try to follow PEP8’s recommendations in all of your programming.

Python Interactive Interpreter

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 (your Python version will be different):

python prompt

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:

python prompt exercise

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)

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:

testing code with the Python interpreter

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'."

no module named Django error

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 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 shell:

starting the Django interpreter

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

exploring django 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.

Comments and Docstrings

Comments are common to most programming languages and are essential to describing code so you or other programmers can understand what is going on when the code is read in future.

Comments in Python are preceded by a hash (#) and a space:

# This is a comment.

Comments can be inline:

x = y + 1	# This is an inline comment

Or single line:

# Define the list of guitarists 
shredders = ["Kirk", "Dave", "Dimebag"]

Python doesn’t have multi-line comments per se—you create multi-line comments by using multiple single line comments:

# This is the first line of the comment,
# This is the second line.
# You can create multi-paragraph comments by
# separating paragraphs with a line containing a single #

Docstrings are a special kind of string used by the Python compiler to create documentation automatically for your modules, classes, methods and functions.

A docstring is the first statement after the declaration of a module, class, method or function. They have two formats; single line:

"""This is a single line docstring"""

And multi-line:

"""This is a multi-line docstring.

The first line is a summary line, followed by a blank line and then a more 
detailed description - often describing arguments, return values, exceptions 
raised and calling restrictions.

The summary statement can be on the same line as the opening triple quotes 
or on the line below.

The closing triple quotes, however, must be on their own line.

The docstring becomes the __doc__ special attribute for the object which is used by many tools and applications, including Django’s admin documentation tool, to create documentation for your code.

For more information on docstrings, see PEP 257.

Math and Numbers

Python has a simple and straight forward approach to programming math and numbers—if you are OK with high school math, you will be OK with Python math.

Carrying on from earlier examples, here are a few more using the Python interactive interpreter (don’t type in the comments, I have added them for your information only):

>>> 50 - 5*6        # Mathematical precedence
20                  # PEMDAS, BEDMAS or BODMAS
>>> (50 - 5) * 6    # depending which country you're from 
>>> 2**10           # Power functions 
>>> import math     # Python math module
>>> r = 10
>>> area = math.pi*(r**2)       # Using pi
>>> area
>>> math.cos(math.radians(60))  # Trigonometry 
>>> math.log(256,2)             # logarithms 
>>> import random               # Python random module
>>> random.random()
>>> random.randrange(12)
>>> random.randrange(12)

Here’s a screenshot of the complete exercise:

Python math exercise

There are dozens more functions you can use to do math and manipulate numbers in Python. For a list of all math functions, check out the Python documentation.

If you want to dig further into math in Python, you can check out the resources below.


A string is simply a sequence of one or more characters—”a” is a string, “Hello There” is a string, if you were silly enough to load it all into a single variable, an entire book could be a string. String characters don’t have to be printable—a string can contain any Unicode character.

Strings are immutable. An immutable object cannot be changed after it’s created. I will be talking more about immutable and mutable objects shortly when I cover lists, tuples and dictionaries.

To create a string, you simply enclose the string in single or double quotes:

x = 'Hello' 
y = "There"

The only time it matters if you use single or double quotes is if there are quotes in the string:

a = 'This doesn't work'      # BAD, will break on
                             # quote in "doesn't" 
b = "Wasn't that easy"       # GOOD
c = '"Air quotes" are silly' # Also GOOD

If there are multiple quotes in the string, you must escape the quotes with a backslash (\):

d = "Aren't quotes \"fun\"?"

Strings are a special class built in to Python, with many class methods available for working with them. Here are a few examples using the Python interactive interpreter:

>>> "hello".capitalize()    # Manipulate a string directly
'Hello'                     # Capitalize string
>>> "hello".upper()         # Uppercase string 'HELLO'
>>> greet = "Hello There"   # Work with string variable
>>> greet[0]                # String indexing
'H'                         # First character
>>> greet[6]
'T'                         # Seventh character
>>> greet[:4]               # String slicing
'Hell'                      # First four characters
>>> greet[len(greet)-4:]
'here'                      # Last four characters
>>> greet[::-1]             # Reverse a string 'erehT olleH'
>>> padded = "    My name is Nige    "
>>> padded.lstrip()

'My name is Nige    '         # Removing whitespace
>>> padded.rstrip()
'    My name is Nige'
>>> greet.replace("e","_")    # Replacing characters
                              # in a string
'H_llo Th_r_'
>>> greet.split()             # Splitting strings
['Hello', 'There']            # Default split is space
>>> greet.split("e")          # But can split on
                              # anything
['H', 'llo Th', 'r', '']

Here’s a screenshot of the exercise:

Python strings exercise

Like math and numbers, this is only a small taste of what can be achieved with the string class. For more information see the Python string class documentation.

Formatting Strings

Another useful thing you can do with strings is to use string interpolation to substitute values into a formatted string. This is easier explained with an example. Try this at the Python prompt:

>>> "There are %s apples left" % "four"

String interpolation is performed with the modulo (%) operator and takes the form:

format % values

So, when you enter the above code, Python replaces the string placeholder (%s) with the string “four”. When you hit enter, Python prints out:

'There are four apples left'

This works on multiple substitutions, however, with multiple substitutions the values must be passed in as a tuple (more on tuples shortly):

>>> "There are %s apples and %s oranges left" % ("four","two")
'There are four apples and two oranges left'

String formatting will substitute numbers as well. For example, %i will insert an integer:

>>> "There are %i apples and %i oranges left" % (2,7)
'There are 2 apples and 7 oranges left'

Other format strings include:

  • %f. A floating point decimal
  • %X. A signed hexadecimal (uppercase)
  • %c. A single character

Here’s a screenshot of the exercise:

Python string formatting exercise

For more on formatting strings, see the Python documentation on String Formatting Operations.

If you want to dig further into strings in Python, you can check out the resources below.

Scroll to Top