Download presentation
Presentation is loading. Please wait.
Published byFelicia Oliver Modified over 9 years ago
1
Branching and Conditions CSIS 1595: Fundamentals of Programming and Problem Solving 1
2
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)
3
Branching Executing statements only under certain conditions Condition: Expression that evaluates to either True or False condition statement in branch statement in branch … statement after branch Do these if condition true Skip if condition false
4
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
5
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
6
Absolute Value Example
7
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)
8
Branching and Indentation “ Negative! ” only printed if number < 0 (inside branch) “ Negative! ” always printed (outside branch)
9
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
10
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
11
Example: Coin Flip
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.