Single Statement Blocks

A Byte of Python

Go to the Table of Contents. Visit the Gifcom web site.

By now, you should have firmly understood that each block of statements is set apart from the rest by its own indentation level. Well, this is true for the most part but it is not 100% accurate. If your block of statements contains only one single statement, then you can specify it on the same line of, say, a conditional statement or looping statement. The following example should make this clear:

>>> flag = True
>>> if flag: print 'Yes'

As we can see, the single statement is used in-place and not as a separate block. Although, you can use this for making your program smaller, I strongly recommend that you do not use this short-cut method except for error checking, etc. One major reason is that it will be much easier to add an extra statement if you are using proper indentation.

Also notice that when the Python interpreter is used in interactive mode, it helps you enter the statements by changing prompts appropriately. In the aboe case, after you entered the keyword if, it changes the prompt to ... to indicate that the statement is not yet complete. When we do complete the statement in this manner, we press enter to confirm that the statement is complete. Then, Python finishes executing the whole statement and returns to the old prompt waiting for the next input.