Killer Web Development

by Marco Laspe

6.2 Python Constructs and Logic

Code Blocks

Code blocks in Python use indentation. Many other programming languages use curly braces for indicate code blocks; not Python. In this book we use 4 spaces, that is the standard in Python. We could use a different amount of spaces or tabs, but 4 spaces are recommended by the Python creators - so we will use it.

Loops and Conditionals

Until now, we had now way to control the flow of our programs. To write useful code we need two types of control structures:

  1. a conditional statement, to choose between different option
  2. an iterative statement,to repeat certain tasks

the if-statement

For conditionals Python uses the if-statement, with the following syntax:

1.
2.
if expression:
code_block

If the expression is true, then the (indented) code block is executed. If not the block is ignored. Let's look at an example:

1.
2.
3.
4.
5.
>>> x = 1 # variable assignment
>>> if x > 0:
...
print "x is greater then 0"
...
x is greater then 0

The if-statement can be also combined with an elif-statement, that allows you to choose from different options:

1.
2.
3.
4.
5.
6.
7.
if expression1:
code_block
elif expression2:
code_block
elif expression3:
code_block
...

An example:

1.
2.
3.
4.
5.
6.
7.
>>> x = 15
>>> if x < 10:
...
print "x is smaller then 10"
... elif x < 20:
...
print "x is smaller then 20"
...
x is smaller then 20

Python also supports the else-statement that gives you an opportunity to choose an default option:

1.
2.
3.
4.
5.
6.
if expression1:
code_block
elif expression2:
code_block
else:
code_block

This way you are able to react to, even if no if-clause fits:

1.
2.
3.
4.
5.
6.
7.
8.
9.
>>> x = 30
>>> if x < 10:
...
print "x is smaller then 10"
... elif x < 20:
...
print "x is smaller then 20"
... else:
...
print "I don't know how big x is."
...
I don't know how big x is.

Loops

Right now we have no way to repeat certain steps. For this Python has to constructs the while-loop and the for-loop. The while-loop is quite similar to the if-statement:

1.
2.
while expression:
code_block

but it executes to code block as long as the conditional expression holds true:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
>>> x = 10
>>> while x < 30:
...
print x
... x = x + 1
...
10
11
...
28
29

Be careful, make sure that the while-loop exits or it will run forever.

The for-loop is a special form of the while loop, that cycles through a sequence:

1.
2.
for element in sequence:
code_block

It is used most often to cycle through a list:

1.
2.
3.
4.
5.
6.
7.
8.
9.
>>> bbt = ["Sheldon", "Lennard", "Raj", "Howard", "Penny"]
>>>
for character in bbt:
...
print ch
...
Sheldon
Lennard
Raj
Howard
Penny

Functions

Functions are junks of code that can be called to perform a certain task. The advantage is that you only have to write it once and can call it as often you want.

The syntax for declaring a Python function is:

1.
2.
def function_name([arguments]):
code_block

A function declaration begins with the keyword def followed by the function name and brackets (function_name()). The rules for the function name are the same as for variables, convention is, that function names start with a small letter. Inside the brackets you can add optional arguments; these are not mandatory.

To create a function that adds 10 to any given number:

1.
2.
3.
4.
5.
6.
7.
8.
>>> def add10(number):
...
result = number + 10
... return result
...
>>>
print add10(5)
15
>>> print add10(10)
20

The function add10 adds 10 to the given number and stores it in the a variable called result; the return statement then returns the result.

Classes

Classes are an important part of object-oriented programming. They build a container for variables and functions (that are called methods), which have a logic connection.

WIKIPEDIA SAYS "Classes on Wikipedia")

Class

In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior. Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior. Class instances are of the type of the associated class.

The syntax of classes:

1.
2.
class ClassName(AncestorClass)
method_declarations

We need classes only for our tests. Let's look at our test suite:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
class TestHomePage (FunctionalTest):

def setUp(self):
# John opens his browser and goes to the home-page of the tukker app
self.url = ROOT + '/tukker/'
get_browser=self.browser.get(self.url)

def test_can_view_home_page(self):
# Let's check if the website was loaded ok => response code == 200
response_code = self.get_response_code(self.url)
self.assertEqual(response_code, 200)
...

This code creates a class TestHomePage that inherits from the class FunctionalTest; then there is a setUP method, that is run before every test, followed by the test methods, that have to begin with the word test. Every method must have the parameter self. Otherwise you will get an error.

The tukker app itself won't use any classes. Classes are an often overused tool. Not everything needs to be class. It makes sense in the case of testing, because that is the way the Python module "unittest" works.

Python in the views

Let's now examine some Python code that we have used in the views so far:

1.
<a id="register-button" href="{{=URL(c="default",f="user",args="register")}}" class="button">Register</a>

This is a simple HTML link; the href attribute of the link takes a simple URL as INPUT. We using web2py's mechanism to write Python code in the views and print the result of the URL function to the HTML code of the view.

  1. We need to use double curly braces ({{...}}) to indicate the stuff inside will be Python code
  2. The equal-sign (=) indicates that the output of the Python code will be added to the views HTML - we will use this a lot.
  3. We call a web2py helper function URL - URL by the way is one of the most important functions in the web2py universe

Books often read by web2py and Python experts:

Comments

Leave a Reply

Required fields are marked *.