Lesson 3. Control structures: selection, iteration and exception handling
Python is famous for having a very clear and beautiful syntax, which promotes readability. Blocks in Python are formatted by just indenting the lines of the blocks; no braces, no parenthesis, no ugly, confusing characters. You just write the corresponding keyword (if, while, etc.) and any other tokens required by the syntax, place a colon (:), then a newline, and indent the lines below by the number of tabs or spaces you want.
keyword and tokens: block statements
The indented lines are part of the new block, and when the Python interpreter finds the first non-indented line, it considers that the block has ended. You should be careful, however, to use a consistent indentation: use only tabs, or only spaces (usually spaces are preferred by many programmers, but that depends on taste); and also pay attention to the number of tabs o spaces you place, because Python expects the same number of them on every line, and may produce an error if a different number of them is found.
Anyway, this is pretty simple for giving such a general explanation, so the best way to look at it is through the examples. But before we move on to examples of Python blocks, you should remember that empty blocks are not allowed in Python: an empty block will be considered a syntax error. If you ever want to write a block that does nothing inside, there is a keyword that does nothing:
pass. We’ll also look at this in the examples.
The if statement
In Python there is only one kind of selection structure: the if statement. There are no
cases or whatever other selection structure you know in another language. And, as we said before, the syntax is quite simple: Just write the
if keyword, then the condition, a colon, and there’s the start of your new block.
if condition: action
But what if you want to perform something when the condition is not met. Of course, the
if statement would be nothing without the
else, and the
else is precisely as simple as the
if condition: # action else: # a different action
Now imagine you want to write an if statement and an else statement, but make the else statement do nothing. You wouldn’t do this normally; if you wanted the else perform no action, you’d just leave it out and not write it at all. But let’s say you need an else but you want to implement it later, because it should perform some actions you must think of carefully. For this purpose, you would use the pass keyword we mentioned before:
if condition: # action else: pass # I'll implement this later
In other situations, you may need the opposite
if do_really_hard_stuff: pass # I'll implement this later else: print "I'm doing the easy stuff"
And as well as there is an else, there should be an else-if. However, in Python this is abbreviated as
if command == 'q': print 'Quitting application' elif command == 'h':: print 'Help message' else: print 'Unknown command'