Branching Part 1 Flashcards
The if statement (2)
What it evaluates and the two paths
-If condition is evaluated to True, the code inside the body of if is executed.
- If condition is evaluated to False, the code inside the body of if is skipped.
The if…else statement (3)
the two consitions/paths+ when we use it
**If the condition evaluates to True,
**the code inside if is executed the code inside else is skipped
**If the condition evaluates to False,
the code inside else is executed
the code inside if is skipped*
used to execute a block of code among two alternatives.
if…elif…else (5)
The paths and when do we use it?
If condition1 evaluates to true, code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, code block 2 is executed.
If condition2 is false, code block 3 is executed.
if we need to make a choice between more than two alternatives, then we use the if…elif…else statement.
Write a program that caculates the area of a triangle
length = int(input(“Enter the length: “))
width = int(input(“Enter the width: “))
area = length * width
print(“Area: “, area)
When is branching used?
When alternative courses of action are possible and each action may produce a different result
Boolean expressions
Memory location that only stores a true or false value
Branches are
+eg
questions with answers that are either true or false
eg. Is it true that the variable num is positive?
Branching structure for ‘if’ cases
its reactions
Reacts differently only for true cases
Branching structure for “if-else” cases
its reaction
reacts differently for the true or false cases
Branching structure for “if-elif-else” cases
Multiple cases possible but only one case can apply, if one case is true then its false that the other cases apply.
body of a branch (2)
what it is+ formatting
- a block of prgram instructions that will execute when a Boolean expression evaluates to/works out to true
- Specified with indenting in python
If you dont follow style convention then it is
a syntax error
Operator/ Operation
Action being performed
*The sign (ex: +)
Operand
The item or items on which the operation is being performed
The number it is operating on
Why is indenting manadartory in python?
To determine which statements are part of a body