Killer Web Development

by Marco Laspe

6.1 Data Types and Variables

The web2py console

To learn Python we will use the web2py console; in the tukker app folder type:

1.
./web2py.py -S tukker # web2py.exe on Windows or web2py.app on OS X

you should see something like the window below. The web2py console is a Python interactive console with the web2py environment added - this means you can access assets from the tukker app.

The web2py console has two modes:

  1. >>> - this mean web2py console expects a new Python statement

  2. ... - this means web2py console needs more input to complete the current statement

Let's see an example:

1.
2.
>>> print "Hello World!"
Hello World!

We used the keyword print to write the String "Hello World!" to the screen. It is really that simple.

Comments

Comments in Python start with a pound sign # and go to the end of the line. They are ignored by the Python interpreter and are only useful for humans :

1.
2.
3.
# no-reload ensures single process
print os.path.curdir
...

the first line tells more about the following code.

Strings

Strings are a set of characters between quotation marks. Python allows pairs of single and double quotation marks, but you are not allowed to mix them up:

1.
2.
3.
4.
5.
6.
7.
8.
9.
>>> print 'Hello World!'
Hello World!
>>>
print "Hello World!"
Hello World!
>>>
print "Hello World!'
File "<console>", line 1
print "Hello World!'
^
SyntaxError: EOL while scanning string literal

print "Hello World!' gives you an error message. If you want to strings with several line breaks, you can use triple quotation marks:

1.
2.
3.
4.
5.
6.
7.
>>> print """This string goes 
... over three
... lines"""
This string goes
over three
lines
>>>

Did you notice the ... for the secondary prompt? The web2py console needs the closing triple of quotation marks to complete the print statement.

You can combine string with the plus sign + :

1.
2.
>>> print "I love" + " " + "web2py."
I love web2py.

The plus sign concatenates the strings. For that reason we need to put in a space between love and web2py.

What to do if you want quotation marks in your strings? Let's say you want to put My name is "Marco". Just use single quotation marks to indicate the string:

1.
print 'My name is "Marco"'

Variables

Python allows you to assign variables. This means you can store values to use them later in you web application and give them names.

Wikipedia says

Variables

In computer programming, a variable is a symbolic name given to a data storage location containing some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents. A variable name in computer source code is an identifier that can be bound to a value during run time, and the value may change during the course of program execution.

Python variables work pretty much like variables in other programming languages:

1.
2.
3.
4.
5.
6.
7.
>>> counter = 0
>>> counter = counter + 1
>>> counter
1
>>> greeting = "Hello World!"
>>> print greeting
Hello World!

Variable names have to begin with an alphabetic letter or an underscore (_), any additional characters have to be alphanumeric. Python variables are cases sensitive:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
>>> GreeTing = "Hello fellow Python programmer."
>>> print GreeTing
Hello fellow Python programmer.
>>>
print greeting
Hello World!
>>>
123_Greeting = "A variable name that isn't allowed!"
File "<stdin>", line 1
123
_Greeting = "A variable name that isn't allowed!"
^
SyntaxError: invalid syntax

Convention tells to begin Python variables to start with a lower case letter!

Operators

Operators in Python work like mathematical operators you know from school:

1.
+   -   *   /

There is also an modulo operator % (remainder) and an exponentiation operator**:

1.
2.
3.
4.
>>> print 10 % 3
1
>>> print 10 ** 3
1000

Python also provides some comparison operators, which return a Boolean value (True or False) of the comparison:

1.
< <= > >= == !=

Let's see some examples:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
>>> 1 < 10
True
>>> 1 <= 1
True
>>> 1 > 10
False
>>> 1 >= 2
False
>>> "String 1" == "String 2"
False
>>> "String 1" != "String 2"
True

Python operators can not only compare numbers, but also can compare strings. Especially the equal (==) and not equal (!=) operators are often used to compare strings.

Lists

A Python lists can be thought of as a container that can hold an arbitrary number of items.

Python List Datatype

The items are ordered and can accessed via an index. List are enclosed in square brackets ([]):

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
>>> list1 = [1, 2, 3, 4]
>>>
list1
[1, 2, 3, 4]
>>>
list1[0]
1
>>> list1[1]
2
>>> list1[3]
4
>>> list1[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> list1.append(5)
>>>
list1
[1, 2, 3, 4, 5]
>>>
list1[2] = 6
>>> list1
[1, 2, 6, 4, 5]

The index of list (and any other sequence) starts with zero! This is important. To get the first item of the list list1 you need to type list [0] - this is important, remember this. The last index of an list is always [-1], the second last [-2] and so on.

Slicing

To get certain parts of a sequence, Python owns a technique called Slicing. The Slicing operator is the colon (:), for example if we want only 3 numbers in the middle of list1 :

1.
2.
>>> list1[1:4]
[
2, 6, 4]

You can also slice the list from beginning or the end of an list, here are a few more examples:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
>>> list1[0:]
[
1, 2, 6, 4, 5]
>>>
list1[1:]
[
2, 6, 4, 5]
>>>
list1[1: -2]
[
2, 6]
>>>
list1[:-2]
[
1, 2, 6]
>>>
list1[:-1]
[
1, 2, 6, 4]
>>>
list1[:]
[
1, 2, 6, 4, 5]

Slicing also works with other Python data types like strings and tuples:

1.
2.
3.
>>> string = "This is a string."
>>> string[0:7]
'This is'

Dictionaries

Dictionaries are another important data type in Python, that allows you to map an key to a value.

Python Dictionary Datatype

The key of an dictionary can be almost any Python type, but usually numbers or strings are used. Values can be any Python object. Dictionaries are enclosed in curly braces ({}):

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
>>> dic = {'title': 'Tukker.Me', 'headline': 'Messages With 300 Chars'}
>>>
dic
{'headline': 'Messages With 300 Chars', 'title': 'Tukker.Me'}
>>>
dic["headline"]
'Messages With 300 Chars'
>>> print dic["headline"]
Messages With 300 Chars
>>> print 'title'
title
>>> print dic['title']
Tukker.Me

Dictionaries are often used by web2py controllers, usually a controller function returns a dictionary (or Dict) and makes it available to the corresponding view.


Books often read by web2py and Python experts:

Comments

Leave a Reply

Required fields are marked *.