Computer Science · Ch 6 — Flow of Control
Summary
Summary
- The order in which the statements of a program are executed is called the flow of control; it is shaped using control structures, of which Python supports two types — selection and repetition.
- The if statement implements selection (decision making):
ifruns a block only when a condition is true,if..elsechooses between two alternative paths, andif..elif..elsechains multiple conditions — the first true condition's block runs and the statement terminates. Anif..elseplaced inside anotherif..elseis a nested if. - Python marks blocks with indentation (leading spaces/tabs), not curly brackets; statements at the same indentation level form one block, and the interpreter enforces indentation strictly.
- The looping constructs while and for allow sections of code to be executed repeatedly under some condition.
- The for statement iterates over a range of values or a sequence; the statements in its body are executed until the range of values is exhausted, after which control passes to the statement following the loop. The number of iterations is known in advance.
- The built-in range([start], stop[, step]) function generates a sequence of integers from
startup to (but excluding)stopin steps ofstep; all parameters must be integers,startdefaults to 0,stepdefaults to 1 and may be negative but never zero. - The statements in the body of a while loop are executed over and over as long as the loop's condition is true; when it becomes false the loop ends.
- If the condition of a while loop is initially false, the body is not executed even once.
- The body of a while loop must ensure that the condition eventually becomes false; otherwise the loop becomes an infinite loop — a logical error in the program. …