Python For Django Programmers – Part 2

In this second tutorial on introductory Python for Django programmers, I will be covering math and string handling in Python, lists, dictionaries and tuples, branching with the if statement and looping with while and for.

This tutorial is an extract from my new book – Build Your First Website with Python and Django.

For your chance to join the launch team and get a 50% discount when the book is launched, see the end of this post.

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:

>>> 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
>>> math.pi*(r**2)
>>> math.cos(math.radians(60))  # Trigonometry
>>> math.log(256,2)             # logarithms
>>> import random               # Python random module
>>> random.random()
>>> random.randrange(12)
>>> random.randrange(12)

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.


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, this whole 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 have to escape the quotes with a backslash (\):

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

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

>>> "hello".capitalize()        # Manipulate a string directly
                                # Capitalize string
>>> "hello".upper()             # Uppercase string
>>> 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'
>>> strPadded = "     My name is Nige   "
>>> strPadded.lstrip()    
'My name is Nige   '            # Removing whitespace
>>> strPadded.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', '']

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 really 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 doesn’t just work with substituting string variables – %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:

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

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

Lists, Dictionaries and Tuples

Lists, dictionaries and tuples are used to store collections of objects. They are differentiated from each other by the delimiter they use:

  • [] – a list. E.g. ["one","two"]
  • {} – a dictionary. E.g. {1:"one", 2:"two"}
  • () – a tuple. E.g. ("one", 2)

Lists you should be very familiar with, as we all use lists daily. A dictionary is also pretty straight forward – think of a regular dictionary where you have the word and then the meaning of the word. In Python, the word is called a key and the definition a value.

Tuples are like lists, with a couple of differences. Lists are designed to contain largely homogeneous data, much like in real life where you would have a shopping list or a to do list. By convention, Python list items should all be the same type (although Python doesn’t enforce this rule).

Tuples, on the other hand, are used to store heterogeneous data – ("one", 2, [three]) is perfectly acceptable as a tuple, where it would be frowned upon as a list. A single element tuple (singleton) is also written differently to a single element list:

lst = ["one"]   # Single element list
tpl = ("one",)  # Single element tuple must have trailing comma
                # to differentiate between a plain string ("one")
                # or a functions parameter some_func("one")

Tuples, like strings, are immutable. Once they are created, you can’t change them. Lists and dictionaries, however, are mutable and can be changed. Let me illustrate with some examples:

>>> lst = ["one"]           # Set up a list, tuple and dictionary
>>> tpl = ("one",)
>>> dict = {0:"one"}
>>> lst[0]                  # All contain the same first element
>>> tpl[0]
>>> dict[0]
>>> lst[0] = "two"          # List is mutable (can be changed)
>>> lst
>>> dict[0] = "two"         # So is the dictionary
>>> dict
{0: 'two'}
>>> tpl[0] = "two"          # Tuple is immutable. Can't change it!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> str = "one"             # String is also immutable
>>> str[0] = "x"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

One last point on tuples vs. lists – tuples are often used for homogeneous data that the programmer doesn’t want changed by accident. So if you have a list of items that should not be changed, it’s can be a good idea to use a tuple instead of a list.

And a final note – if you want to see a number of examples on how lists and dictionaries are used in Django, check out your project’s file.

The if Statement and Code Branching

Python, like most programming languages, has an if statement that provides branching in your code. The syntax of Python’s if statement is as follows:

if [expression is True]:
    # execute this code when True
    # execute this code when False

The else branch is optional:

if [expression is True]:
    # only executes when True

# resume code execution

The expression can be anything that evaluates to True or False. A few examples:

  1. if num >= 10:
  2. if str == "Hello:
  3. if this != that:
  4. if SomeVar:

… and so on.

Take note of example 4 above – in Python, anything that does not equate to zero, Null, or an empty object is True. So this works:

>>> s = 0
>>> if s:
...     print('T')
>>> s = 1
>>> if s:
...     print('T')
>>> s = ""
>>> if s:
...     print('T')
>>> s = "Hello"
>>> if s:
...     print('T')

Python includes a comprehensive range of boolean operators that you can use within your expressions:

  • <– Less than
  • <= – Less than or equal
  • >– Greater than
  • >= – Greater than or equal
  • == – Equal
  • != – Not equal
  • is – Is a particular object
  • is not – Isn’t a particular object

Boolean operations are also supported for negating and chaining expressions:

  • or– Either expression can be True
  • and – Both expressions must be True
  • not – Negate the proceeding expression

Python also supports multiple branching using the elif (else if) statement:

if [exp1 is True]:
    # execute if exp1 is True
elif [exp2 is True]:
    # execute if exp2 is True
elif [exp3 is True]:
    # execute if exp3 is True
# and so on ...
    # execute this code when all else fails

Loops and Iterators

Loops and iterators both do the same basic thing – repeat a section of code until some condition is met. With a loop, the repetition can be any arbitrary code sequence, whereas an iterator steps through an iterable object. An iterable object is an object that can be indexed (stepped through) in a sequential way. The most common iterable types in Python are the sequence types – strings, lists, tuples and ranges.

The while Loop

To create a program loop in Python, you use the while statement. For example, here is a very simple loop:

a = 1
while a < 5:

This should be easy to follow:

  1. Set the value of a to 1.
  2. Start a loop with the while statement
  3. Print out the current value of a
  4. Increment a
  5. Repeat while the expression a < 5 is True.

If you run this code at the Python prompt, your output should look like this:

>>> while a < 5:
...     print(a)
...     a+=1

Python’s while loops are very useful and can be used for much more than simple tasks like printing out a variable. For example, the factorial (!) of any number is simply the multiplication of the number and all the preceding integers (so 4! is equal to 1*2*3*4). Here’s how to calculate the factorial of 9 with a while loop:

fact, mul = 1, 2    # Multiple assignment
while mul < 10:
    fact, mul = fact*mul, mul + 1

In the first line I am using multiple assignment, which is a useful feature of Python’s programming syntax. The statement fact, mul = 1, 2 is a shorthand way of writing:

fact = 1
mul = 2

Line 3 is where all the magic happens, first we multiply the current value of fact by mul and then we increment mul by 1. We then print out the new value of fact. If you run this at they Python prompt, you should see something like this:

>>> fact, mul = 1, 2
>>> while mul < 10:
...     fact, mul = fact*mul, mul + 1
...     print(fact)

Breaking out of Loops

The break and continue statements allow you to exit a loop before the loop condition is met. Consider the following code:

a, b = 1, 1
while a < 5:
    print("a =", a)
    a +=1
    while b < 5:
        print("b = ", b)
        if b == 2:
            b = 1
        b +=1

The break statement will only exit the currently running loop, so in the above example the break statement only exits the inner while loop. Let’s see what the output is when we run this code:

>>> while a < 5:
...     print("a =", a)
...     a +=1
...     while b < 5:
...         print("b = ", b)
...         if b == 2:
...             b = 1
...             break
...         b +=1
a = 1
b =  1
b =  2
a = 2
b =  1
b =  2
a = 3
b =  1
b =  2
a = 4
b =  1
b =  2

You can see that the break statement doesn’t affect the outer loop – it continues to run until a < 5 is False. Because the inner loop always breaks when b is equal to 2, the inner while loop never completes.

The continue statement, on the other hand, won’t execute any of the code after the continue statement, but instead it jumps to the next iteration of the loop. Consider the following code:

a = 0
while a < 5:
    if a == 3:
        print("My favorite number is", a)
        continue    # Go to next iteration of loop
    print("a =", a)  # The continue statement will stop
                    # this from printing when a equals 3

Run this code and you should see the different string printed when a equals 3:

>>> a = 0
>>> while a < 5:
...     a+=1
...     if a == 3:
...         print("My favorite number is", a)
...         continue
...     print("a =", a)
a = 1
a = 2
My favorite number is 3
a = 4
a = 5

The break and continue statements can also be used inside a for loop.

Iterating with a for Loop

The for loop is designed to step through an iterable item. It takes the basic form:

for [item] in [iterable]:

As I said earlier in the chapter, the most common iterables are strings, lists, tuples and ranges. Here are some examples:

>>> word = "Hello"
>>> for char in word:   # Step through each character in the word
...     print(char)
>>> lst = ['1','2','3'] # Step through each item in the list
>>> for item in lst:
...     print(item)
>>> tup = (1,"two", 3)  # Step through each item in the tuple
>>> for item in tup:
...     print(item)
>>> for i in range(5):  # The range function provides you
...     print(i)        # with a sequence of integers

This should all be easy to follow. The range() function we haven’t covered, but it’s basically an easy way of creating a sequence of numbers. More on the range() function in the Python documentation.

Want my new Django book for beginners for half price?

I have a new book for beginners coming out very soon (by end of June if all goes to plan!).

In this new book I answer the big questions I get from beginners:

  • Why should I use Django?
  • What problems does Django help me solve?
  • What if I don’t know Python?
  • Please, can you give me something real? Something I can build and show off to my friends, or a potential employer – not just snippets like everyone else on the Internet?

Written for Django 1.11 and Python 3.6, the book teaches you to program using the absolute latest version of Django and Python.

By the end of the book you will not only know all of the basics to writing an awesome Django website, but you will have a functioning website ready for deployment, or to demonstrate to an employer – Or to show off to your friends 🙂

Anyone who signs up below will not only get to be a part of an exciting book launch, but will get the eBook version for half price as a part of a limited time launch special!

Will send you more information by email closer to launch day.