statements to be executed if true

Branching and Conditions
CSIS 1595: Fundamentals of
Programming and Problem Solving 1
Sequential Program Flow
• Sequential flow:
– Statements executed one after another from beginning to
end of program
•
•
•
•
Statement 1
Statement 2
Statement 3
…
• Python syntax: By default statement ends at end of line
– Other languages have symbols to indicate statement end ;
– Can use \ to continue statement onto multiple lines (readbility)
distance = math.sqrt((x1 – x2)**2 \
(y1 – y2)**2)
Branching
• Executing statements only under certain conditions
• Condition:
Expression that evaluates to either True or False
condition
statement in branch
Skip if
statement in branch
condition
false
…
statement after branch
Do these if
condition true
Absolute Value
• Requirement: Input number and print its absolute value
• Pseudocode:
1. Input number (converting to float)
2. If the number is less than 0, multiply itself by -1
3. Print the number
• Condition: If the number is less than 0
• Statements executed only if true:
multiply itself by -1
Python Syntax
if condition:
statement to be executed if true
statement to be executed if true
statement to be executed if true
…
first statement executed regardless
• condition is a boolean expression
• Indentation used to indicate what is part of branch
Absolute Value Example
Branching and Indentation
• How does Python know where a branch ends?
• Indentation used in Python
– Lines after if indented only executed if condition true
– Other languages use { … }, etc.
• Readability:
All statements in same branch should be lined up
(same indentation)
Branching and Indentation
• “Negative!”
only printed if
number < 0
(inside branch)
• “Negative!”
always printed
(outside
branch)
If-Else Branching
• Executing another set of statements if condition false
if condition:
statements to be executed if true
…
else:
statements to be executed if false
…
first statement executed regardless
Example: Coin Flip
• Goal: Randomly print “Heads” or “Tails”
• random module: simple random number generators
– random.random()  random float between 0 and 1
• Algorithm:
–
–
–
–
Generate random number between 0 and 1
If number > 0.5, print “Heads”
Otherwise, print “Tails”
In either case, print “Thanks for playing” afterwards
Example: Coin Flip