Python Programming: Part Three (Conditional Statements; Lists, Tuples and Dictionaries)

Python listIn the previous article, we covered variables, and how to save and run Python modules. In this article, we will introduce some more basic concepts including statements that alter the control flow of Python, and lists, tuples and dictionaries.

Up to this point, we have been executing Python statements using a linear control flow. A programming language is of minimal value, however, without conditional statements. Python provides three such statements: if, elif, and else. For example:

>>> if x < 0:
                print(‘x is a negative number’)

In this example, we used the comparison operator “<” (less than) to test to see if x is less than 0. If x is less than zero, we will print a statement that tells us x is a negative number. We might also want to print something out if x is zero or positive:

>>> if x < 0:
               print(‘x is a negative number’)
         elif x == 0:
                print(‘x equals zero’)
         else:
                print(‘x is a positive number’)

Here, the first two lines are the same, but if x is not less than zero, we test it to see if it is equal to zero and if it is, we print a message. If x is not less than zero or zero, we assume it is positive and print another message. Another useful control flow statement is the for statement. The for statement in Python differs a bit from the for statement in C and Pascal. Rather than always iterating over an arithmetic progression of numbers, as in Pascal, or giving the user the ability to define both the iteration step and halting condition as in C, Python’s for statement iterates over the items of any sequence in the order that they appear in the sequence. For example:

>>> word = ‘coffee’
>>> for c in word:
                 print(c)

This will print every letter in the string word on a separate line. If you need to iterate over a sequence of numbers, the built in function range() comes in handy. It generates arithmetic progressions:

>>> for i in range(10):
                 print(i,’ ‘,i**2)

This code will print out two columns: one containing integers 0 through 9, the other containing their squares. If you specify only a single parameter, 0 will be the lower bound and the specified parameter will be the upper bound. But you can specify a lower bound:

>>> for i in range(5,10):
                print(i,’ ‘,i**2)

This code will print out integers 5 through 9 and their squares. We can also specify a step value:

>>> for i in range(1,10,2):
                 print(i,’ ‘,i**2)

This code will print out all odd-numbered integers from 1 through 9 and their squares.

Lists, Tuples and Dictionaries

In C, there are arrays, which act as a compound data type. In Python, there are two sequence types not yet covered: lists and tuples. There are also dictionaries, which is not a sequence type, but is nonetheless very useful.

Lists are collections of some data type. Creating a list can be done quite easily:

>>> mylist = [5, 10, 15]

This will create a list with three items in it. We can iterate through the list as well:

>>> for i in mylist:
                 print(i)

This will print each item in mylist on a separate line. You can use the assignment operator on a list:

>>> otherlist = mylist

Now we will be able to access the list, but it is important to note that otherlist is not a separate copy of mylist. It also points to mylist. So this statement:

>>> otherlist[0] = 100

will alter the contents of mylist:

>>> print(mylist)
[100, 10, 15]

You can also nest a list within a list. For example:

>>> secondlist = [1, 2, 3, 4]
>>> mylist[0] = secondlist

nests secondlist inside mylist as the first element.

You can also create an empty list, by specifying an empty set of brackets in the assignment, like this:

mylist = []

Lists have a built-in method called append that can be used to append an item to the end of a list:

>>> mylist.append(125)

appends 125 to the end of the list.

Whereas a list is a mutable sequence data type, a tuple is an immutable sequence data type. A tuple consists of a number of values separated by commas. For example:

>>> tu = 1, 2, 3

A tuple need not contain all the same data type. The following statement is valid:

>>> tu = 5, 10, 15, ‘twenty’

To confirm that tuples are immutable, we can try to change one of the items:

>>> tu[0] = 121
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘tuple’ object does not support item assignment

On output, tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parenthesis, although often parenthesis are necessary anyway if the tuple is part of a larger expression. It is not possible to make an assignment to an individual item of a tuple; however, it is possible to create tuples which contain mutable objects, such as lists.

Another useful data type built into Python is the dictionary. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type. Strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You cannot use lists as keys, since lists can be modified.

You can think of dictionaries as unordered sets of key: value pairs, with the requirement that the keys are unique within one dictionary. A pair of braces creates an empty dictionary. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary.

Here is an example of a dictionary:

>>> generals = { ‘Germany’: ‘Hindenburg’, ‘Russia’: ‘Samsonov’, ‘France’: ‘Nivelle’, ‘United Kingdom’: ‘Haig’ }
>>> print(generals[‘Germany’])
‘Hindenburg’
>>> del generals[‘Russia’]
>>> generals[‘France’] = ‘Foch’
>>> print(generals)
{‘Germany’: ‘Hindenburg’, ‘France’: ‘Foch’, ‘United Kingdom’: ‘Haig’}

You can use for to iterate through a dictionary. For example:

>>> for c in generals.keys()
print(generals[c])

Hindenburg
Foch
Haig

In the next article, we will introduce the concept of modules, and write our first function.

External Links:

Python documentation from the official Python website

Python Programming: Part One

Python programmingPython, as mentioned earlier, is an interpreted language. An interpreter is a program that executes other programs, and when you are doing Python programming, the Python interpreter reads your program and carries out the instructions it contains.

In its simplest form, a python program is just a text file containing Python statements. For example, the initial “Hello, world” program from the previous article is a very simple Python script, but it passes for a fully functional Python program:

print(‘Hello, world!’)

This program contains a single Python print statement, which simply prints a string to the output stream, and thus is a very simple example of Python programming. We can also output the results of numeric expressions if we want:

print(3+5)

This will print an “8” to the output stream.

Python Programming: Running Python Programs

Perhaps the easiest way to begin Python programming is to type in programs at Python’s interactive command line. There are many ways to do this: start it in an IDE, from a system console, and so on. Assuming that Python is installed on your system (we covered installation in a previous article), the simplest and most platform-neutral way to start the Python interpreter is usually just to type python at your operating system’s prompt, without any other arguments. The notion of a system shell prompt is cross-platform, but how you access it varies by platform:

  • In Windows, you can type python in a DOS console window (the Command Prompt), found in the Accessories section of the Start -> Programs menu, by right mouse-clicking on the window icon on the lower left corner of the screen in Windows 8, or in the Start -> Run dialog box (run “cmd.exe”).
  • On Unix/Linux/Mac OS X, you might type this command in a shell or terminal window.
  • On handheld devices, you generally click the Python icon in the home or application window to launch an interactive session.

If you have not set your shell’s PATH environment variable to include Python’s install directory, you may need to type the full path to the Python executable on your machine (e.g. c:\Python34\python in Windows for version 3.4). The installer should update the path, however, and I have not had to type the full path under Windows or Linux. Of course, you can always use the change directory command to go to the Python install directory.

In Windows, you can also begin interactive sessions for Python programming by starting IDLE’s main window or by selecting the “Python (command line)” menu option from the Start button menu (in Windows 7 and earlier). I made a desktop shortcut for Python in Windows 8. Both the command line Python interpreter and IDLE spawn a Python interactive prompt with equivalent functionality.

When coding at the Python interactive prompt, we can type as many Python commands as we want, and each command will be run immediately after it is entered:
>>> print(‘Hello, world!’)
Hello, world!
>>> a = 3+4
>>> print(a)
7
The first command prints: Hello, world!. The second command assigns the sum of 3+4 to the variable a, and the third command prints out the value of a. Note that because the interactive session automatically prints the results of expressions you type, so you do not even need to say “print” at the prompt:
>>> a
7

We did not do much with the code in this article, but hopefully it served as an adequate introduction to Python programming, and the main point we want to remember here is that the interpreter executes the code entered on each line immediately, when the [ENTER] key is pressed. There is no need to create a source code file, and no need to run the code through a compiler and linker first, as you would do with a language such as C or C++. As we will see in future articles, you can also run multi-line statements at the interactive prompt. Such statements run immediately after you’ve enter all of its lines and pressed [ENTER] twice to add a blank line.

External Links:

The official Python site – contains many useful resources for Python programming.