Comp 112

Lecture 3

Flow Control


Conditional Execution

Alternative Execution

Chained Conditionals

Multiple Alternatives

We can add an else clause to a chained conditional:

if <first_guard> :
elif <second_guard> :

elif <last_guard> :
else :

General Form of if Statements

The most general form of an if statement has:

Example: Guessing Game

Let’s think of something and have Python guess what it is.

Complex Conditionals

The branching structure of conditionals can be arbitrarily complex.

But complicated conditional statements can get confusing: How do we know if it’s a leap year?

Boolean expressions help to simplify conditional structure.

Conditional Expressions

You can also write conditional expressions:

<true_expression> if <boolean_guard> else <false_expression>

so instead of:

we can write:

Tip: If you want to become a really good programmer, look for opportunities to replace statements with expressions.

Expressions are more flexible because they are data that can be manipulated by your program, in contrast, statements can only be executed.

Repeated Execution

How While Loops are Executed

i  =  0
print ("Here we go...")
while i < 3 :
    print ('One more time!')
    i = i + 1
print ("O.K. I'm done now.")

When control reaches a while statement:

Example: Computing Factorial by Iteration

We can compute the factorial (mathematical) function (i.e. n!=n×(n1)×(n2)××1n! = n × (n−1) × (n−2) × ⋯ × 1) by iteration.

Augmented Assignment

Drawing Polygons using Iteration

Validating User Input

Using loops and conditionals together we can validate user input:

To Do This Week: