>>> for p in mylist: print p
...
andi
rasmus
zeev
Without the comma after the print
statement, each item is printed on its own line. The other loop type is the while
loop, and it looks similar:
>> while 1: print 'This will loop forever!'
...
This will loop forever!
This will loop forever!
This will loop forever!
This will loop forever!
This will loop forever!
(etc)
Traceback (most recent call last):
File '<stdin>', line 1, in ?
KeyboardInterrupt
>>>
That is an infinite loop (it will carry on printing that text forever), so you have to press Ctrl+C to interrupt it and regain control.
If you want to use multiline loops, you need to get ready to use your Tab key: Python handles loop blocks by recording the level of indent used. Some people find this odious; others admire it for forcing clean coding on users. Most of us, though, just get on with programming!
For example:
>>> i = 0
>>> while i < 3:
... j = 0
... while j < 3:
... print 'Pos: ' + str(i) + ',' + str(j) + ')'
... j += 1
... i += 1
...
Pos: (0,0)
Pos: (0,1)
Pos: (0,2)
Pos: (1,0)
Pos: (1,1)
Pos: (1,2)
Pos: (2,0)
Pos: (2,1)
Pos: (2,2)
You can control loops by using the break
and continue
keywords. break
exits the loop and continues processing immediately afterward, and continue
jumps to the next loop iteration.
Functions
Other languages — such as PHP — read and process an entire file before executing it, which means you can call a function before it is defined because the compiler reads the definition of the function before it tries to call it. Python is different: If the function definition has not been reached by the time you try to call it, you get an error. The reason behind this behavior is that Python actually creates an object for your function, and that in turns means two things. First, you can define the same function several times in a script and have the script pick the correct one at runtime. Second, you can assign the function to another name just by using =
.
A function definition starts with def
, followed by the function name, parentheses and a list of parameters, and then a colon. The contents of a function need to be indented at least one level beyond the definition. So, using function assignment and dynamic declaration, you can write a script that prints the correct greeting in a roundabout manner:
>>> def hello_english(Name):
... print 'Hello, ' + Name + '!'
...
>>> def hello_hungarian(Name):
... print 'Szia, ' + Name + '!'
...
>>> hello = hello_hungarian
>>> hello('Paul') Szia, Paul!
>>> hello = hello_english
>>> hello('Paul')
Notice that function definitions include no type information. Functions are typeless, as we said. The upside of this is that you can write one function to do several things:
>>> def concat(First, Second):
... return First + Second
...
>>> concat(['python'], ['perl'])
['python', 'perl']
>>> concat('Hello, ', 'world!')
'Hello, world!'
That demonstrates how the return
statement sends a value back to the caller, but also how a function can do one thing with lists and another thing with strings. The magic here is being accomplished by the objects. You can write a function that tells two objects to add themselves together, and the objects intrinsically know how to do that. If they don't — if, perhaps, the user passes in a string and an integer — Python catches the error for you. However, it is this hands-off, 'let the objects sort themselves out' attitude that makes functions so flexible. The concat()
function could conceivably concatenate strings, lists, or zonks — a data type someone created herself that allows addition. The point is that you do not limit what your function can do — clichй as it might sound, the only limit is your imagination!
Object Orientation
After having read this far, you should not be surprised to hear that Python's object orientation is flexible and likely to surprise you if you have been using C-like languages for several years.
The best way to learn Python OOP is to just do it. So, here is a basic script that defines a class, creates an object of that class, and calls a function:
class dog(object):