110 likes | 263 Views
Branching and Conditions. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Sequential Program Flow. Sequential flow: Statements executed one after another from beginning to end of program Statement 1 Statement 2 Statement 3 …
E N D
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 statement in branch … statement after branch Do these if condition true Skip if condition false
Absolute Value • Requirement: Input number and print its absolute value • Pseudocode: • Input number (converting to float) • If the number is less than 0, multiply itself by -1 • 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 truestatement to be executed if truestatement to be executed if true … first statement executed regardless • conditionis a boolean expression • Indentation used to indicate what is part of branch
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