Control Structures


In order to write more interesting scripts, you will need to know about control structures.

if Statements

An if statement tests to see if a condition is true. If it is, the block of code following it is executed. This example tests to see if the value of x is less than 0. If so, x is multiplied by 1 to make it positive:

 if x < 0 :     x *= −1

The important thing to note here is that there are no begin/end delimiters (such as curly braces) to group the statements following if. Instead, the test is followed by a colon (:), and the block of code is indented. As mentioned earlier, Python is sensitive to indentation. When you are done with the if statement, you simply return to entering your code in the first column.

When you enter the first line of an if statement in the interactive interpreter, it will prompt you with “” for the remaining lines. You must indent these lines, just as you would if you were entering them in a script. To end your if block, just enter a blank line. The preceding if statement would look like this in the interpreter:

 >>> if x < 0 : ...    x *= −1 ...

if statements can have an else clause that gets executed if the initial condition is not met. This example checks whether a dictionary contains a particular key:

 if dict.has_key(key):     print "%s is in dict" % key else:     print "%s could not be found. Adding %s to dictionary..." % (key, key)     dict[key]=value

You can also include elif clauses that test additional conditions if the first one is false. This example has one elif clause:

 if str.islower() :       print str, "is all lower case" elif str.isupper() :       print str, "IS ALL UPPERCASE" else :       print str, "Combines Upper And lower case letters"

Comparison Operators

The comparison == is used to see if two values are equal. Unlike other languages, Python allows you to use the same comparison operator for strings and other objects as well as for numbers. But be careful not to use =, which in the next example would set x to 0. To test whether two values are different, you can use !=, which also works on any type of object.

Python uses the keywords and, or, and not for the corresponding logical tests, as in this example:

 if x == 0 or y == 0 :     print "Cannot divide by 0." elif not (x > 0 and y > 0) :     print "Please enter positive values."

for Loops

The for loop iterates through the elements of a list. This example will print each list element on its own line:

 for element in list: print element

The syntax here could be read as “for each element in the list, print the element”.

As you will see in the section “Input and Output”, for loops are very useful for looping through the lines in a file. They can also be used with ranges, to execute a loop a certain number of times. For example,

 for i in range (10):       print "%d squared is %d" % (i, i**2)

will use the list [0, 1, 2, 3,... 9] to print the squares of the integers from 0 to 9. To create the list [1, 2, 3, 10], you could use range(1, 11).

The for loop is also handy for working with dictionaries. This loop will iterate through the keys of a dictionary and print each key/value pair:

 for key in userinfo.keys() :       print key, "−>", userinfo [key]

while Loops

The while loop repeats a block of code as long as a particular condition is true. For example, this loop will repeat five times. It will halt when the value of n is 0.

  (n, sum)=(5, 0) while n > 0 :      sum += n      n −= 1

To create an infinite loop, you can use the keyword True or False. You can exit from an infinite loop with break. This loop, for example,

 while True :     print inputlist.pop(0)     if inputlist[0] == "." :         break

will print each element in inputlist. When the next element in the list is ".", the loop will terminate.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net