Python Programming Language

Control Structures

By

First published on October 10, 2019. Last updated on February 16, 2020.


Control structures are used to make various things happen, typically depending on particular conditions. These are also called decision structures. The program examines one or more conditions, decides on a part of action to take, then executes that path. A control structure typically starts with a condition statement (which acts as a question). For example, the program might ask if a certain thing is true, such as if a variable is over 20. Then the control structure will state a course of action (path) if the condition is true. Sometimes there will be an alternate path if the condition is false. Some control structures allow for multiple conditions.

White Space

One way that Python is readable is that it uses spaces (white space) for certain structures. This results in less jargon and well-organized program text. However, if you do not follow white space rules, your program will often not work. Some parts of control structures must be intended, Typically the indentation is four spaces or one tab.

White Space Example

Below is an example of a simple control structure. It does something as long as x is in the range. This is useful where x does not merely increase iteratively, but rather represents some situational quantity encountered, such as the size of an image. Also notice the the action is intended to indicate that it is performed as part of that control structure. Without the indentation, the action would be executed regardless of the result of the control condition.

for x in range(0, 100):
    
    # Do something.

Further Reading


COURSE


Content is copyright the author. Layout is copyright Mark Ciotola. See Corsbook.com for further notices.