Книга: Fedora™ Unleashed, 2008 edition

Conditionals and Looping

Conditionals and Looping

So far, we have been looking at just data types, which should show you how powerful Python's data types are. However, you simply cannot write complex programs without conditional statements and loops.

Python has most of the standard conditional checks, such as > (greater than), <= (less than or equal to), and == (equal), but it also adds some new ones, such as in. For example, you can use in to check whether a string or a list contains a given character/element:

>>> mystring = "J Random Hacker"
>>> "r" in mystring
True
>>> "Hacker" in mystring
True
>>> "hacker" in mystring
False

The last example demonstrates how in is case sensitive. You can use the operator for lists, too:

>>> mylist = ["soldier", "sailor", "tinker", "spy"]
>>> "tailor" in mylist
False

Other comparisons on these complex data types are done item by item:

>>> list1 = ["alpha", "beta", "gamma"]
>>> list2 = ["alpha", "beta", "delta"]
>>> list1 > list2
True
list1
's first element (alpha) is compared against list2's first element (alpha) and, because they are equal, the next element is checked. That is equal also, so the third element is checked, which is different. The g in gamma comes after the d in delta in the alphabet, so gamma is considered greater than delta and list1 is considered greater than list2.

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.

Оглавление книги

Оглавление статьи/книги

Генерация: 0.108. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз