Выбрать главу

Loops come in two types, and both are equally flexible. For example, the for loop can iterate through letters in a string or elements in a list:

>>> string = "Hello, Python!"

>>> for s in string: print s,

...

H e l l o , P y t h o n !

The for loop takes each letter in string and assigns it to s. The letter is then printed to the screen when you use the print command, but note the comma at the end: this tells Python not to insert a line break after each letter. The "..." is there because Python allows you to enter more code in the loop; you need to press Enter again here to have the loop execute.

The same construct can be used for lists:

>>> mylist = ["andi", "rasmus", "zeev"]

>>> 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):

 def bark(self):

  print "Woof!"

fluffy = dog()

fluffy.bark()

Defining a class starts, predictably, with the class keyword, followed by the name of the class you are defining and a colon. The contents of that class need to be indented one level so that Python knows where each class stops. Note that the object inside parentheses is there for object inheritance, which is discussed later. For now, the least you need to know is that if your new class is not based on an existing class, you should put object inside parentheses as shown in the previous code.

Functions inside classes work in much the same way as normal functions do (although they are usually called methods), with the main difference being that they should all take at least one parameter, usually called self. This parameter is filled with the name of the object on which the function was called, and you need to use it explicitly.

Creating an instance of a class is done by assignment. You do not need any new keyword, as in some other languages — you just provide empty parentheses. You call a function of