You are on page 1of 26

Branching Statements

Types of Control Flow in Python


In Python programming language, the type of control flow statements
is as follows:
• The if statement
• The if-else statement
• The nested-if statement
• The if-elif-else ladder
Lesson objectives
1. Use conditional statements in Python, including the “if”,
“if…else”, and “if…elif” statements
2. Use Boolean logic to create complex conditionals
3. Use the “for” statement to create loops

4/18/09 3
Conditional execution (if…)
• Syntax:
if condition:
do_something
• Condition must be statement that evaluates to a boolean
value (True or False)

4/18/09 4
Decision Making With An ‘If’
True
Question? Execute a statement
or statements

False

Remainder of
the program

slide 5
Example:
Checking user input
x = raw_input("X? ")
if x.isdigit():
print("You input a number“)

4/18/09 6
Alternative execution
• Syntax:
if condition:
do_something
else:
do_alternative

4/18/09 7
Decision Making With An ‘If-Else’
True
Question? Execute a statement
or statements (if body)

False

Execute a statement
or statements (else body)

Remainder of
the program

slide 8
The If-Else Construct
Decision making: checking if a condition is true (in which case something should be done) but unlike
‘if’ also reacting if the condition is not true (false).
Format:
if (operand relational operator operand):
body of 'if'
else:
body of 'else'
additional statements

slide 9
Example:
Checking user input
x = input("x? ")
if x.isdigit():
print("You input a number“)
else:
print("Please input a number next
time“)

4/18/09 10
Example:
Avoiding division by zero
x = int(input("x? "))
y = int(input("y? "))
if y!= 0:
print(x / y)
else:
print("Attempted division by zero“)

4/18/09 11
Chained conditionals
• Syntax:
if condition:
do_something
elif condition:
do_alternative1
else:
do_alternative2

4/18/09 12
Example:
x = int(input("x? "))
y = int(input("y? "))
if x < y:
print('x is less than y’)
elif x > y:
print( 'x is greater than y’)
else:
print('x and y are equal’)
4/18/09 13
Nested Decision Making
Decision making is dependent. The first decision must evaluate to true (“gate keeper”)
before successive decisions are even considered for evaluation.

True True Statement or


Question 1? Question 2?
statements

False
False

Remainder of
the program

slide 14
Nested Decision Making
• One decision is made inside another.
• Outer decisions must evaluate to true before inner decisions are even considered for
evaluation.
• Format:
if (Boolean expression):
Outer body
if (Boolean expression):
Inner body
body

slide 15
Nested Decision Making (2)
• Partial example: nesting.py
if (income < 10000):
if (citizen == 'y'):
print("This person can receive social assistance")
taxCredit = 100
tax = (income * TAX_RATE) - taxCredit

slide 16
Notes on conditionals
• You have to have at least one statement inside each branch but you
can use the pass command while stubbing
if x < 0:
pass #Handle neg values

4/18/09 17
Notes on conditionals
• You can have as many elif branches as you need
• This replaces the select and switch commands in other languages
• Conditionals can be nested
• Example: nested.py

4/18/09 18
Complex condition statements
• Use Boolean logic operators and, or, and not to chain together
simple conditions
• Example: boolean.py

4/18/09 19
What Decision Making Mechanisms Are Available /When To Use Them

Mechanism When To Use

If Evaluate a Boolean expression and execute some code


(body) if it’s true
If-else Evaluate a Boolean expression and execute some code
(first body: ‘if’) if it’s true, execute alternate code (second
body: ‘else’) if it’s false
Multiple Multiple Boolean expressions need to be evaluated with
if’s the answer for each expression being independent of the
answers for the others (non-exclusive). Separate
instructions (bodies) can be executed for each expression.
If-elif- Multiple Boolean expressions need to be evaluated but
else zero or at most only one of them can be true (mutually
exclusive). Zero bodies or exactly one body will execute.
Also it allows for a separate body (else-case) to execute
when all the if-elif Boolean expressions are false.
slide 20
When To Use Compound And Nested
Decision Making
Mechanism When To Use

Compound There may have to be more than one condition to be


decision considered before the body can execute. All
making expressions must evaluate to true (AND) or at least
one expression must evaluate to true (OR).
Nested The outer Boolean expression (“gate keeper”) must
decision be true before the inner expression will even be
making evaluated. (Inner Boolean expression is part of the
body of the outer Boolean expression).

slide 21
The for loop
• Used to repeat a section of code a set number of times
• Syntax:
for target in sequence:
do_statements

4/18/09 22
Example: (power.py)
def power(base, exponent):
val = base
for x in range(1,exponent):
val = val * base
print val

power(3,4)

4/18/09 23
Example: (power.py)
def power(base, exponent):
val = base
for x in range(1,exponent):
print x, val
val = val * base
print val

4/18/09 24
Example: (power.py)
def power(base, exponent):
val = base
for x in range(1,exponent):
print x, val
val = val * base
print val

4/18/09 25
Exercises
1. Find a major bug in the power function and correct it
2. Add a docstring to the power function
3. Add type checking and value checking to the power function

4/18/09 26

You might also like