|
|
|
|
|
Lesson 3: Control Flow in Python
- Control flow
refers to altering the path taken through a program. Since Python
executes a program line by line in sequential order, any statements
that alter this path are known as control-flow statements. In
Python, these statements are the if statement, while loop, and for loop [ 2:79].
if Statements
- The if statement has the syntax:
if condition:
- # Do something.
elif another_condition:
- # Do something else.
else: - # Do something other than two options above.
- The elif and else clauses are optional. The condition and another_condition
tests can be a comparison statement (using logical or comparison
operators) or a single variable. Since Python does not have a
Boolean type, every type has Boolean properties. The values 0, ""
(empty string), [ ] (empty list), { } (empty dictionary), and ( )
(empty tuple) equal a logical false. Every other value equals a logical true.
Notice that Python does not use BEGIN/END or curly braces, { },
to denote compound or nested statments. This is indicated through
indentation only [4].
Code Example 3.1 demonstrates the proper use of the if statement. Note the use of the logical and comparison operators from Lesson 2.
while Loops
- The while loop has the syntax:
while condition:
- # Do something.
else: - # Do something else.
- The else clause is optional. In a while loop, the nested statement is repeated until the condition is false. The same properties for condition apply for while loops as they did for if statements. Code Example 3.2 shows a simple parse using a while loop and nested if statement.
for Loops
- The for loop has the syntax:
for item in objects:
- # Do something.
else: - # Do something else.
- The else clause is optional. In a for loop, the nested statement is repeated until objects is exhausted. Each iteration the loop steps through the objects in a sequential order and item is assigned the value of an element of objects. If the loop is a counter from 0 to n, then the built-in function range(n + 1 ) can be called in place of objects. Code Example 3.3 shows simple counters using for loops and the range(n) function.
-
Now that we can control the data and flow of programs, we will look at
breaking our programs into functions. We have already called a
built-in function, range(n), and in the next section, we will look at creating our own.
To Lesson 4 ...
|
|