Topics • The if Statement • The if-else Statement • Comparing Strings • Nested Decision Structures and the if-elif-else Statement • Logical Operators • Boolean Variables • Turtle Graphics: Determining the State of the Turtle
The if Statement • Control structure: logical design that controls order in which set of statements execute • Sequence structure: set of statements that execute in the order they appear • Decision structure: specific action(s) performed only if a condition exists • Also known as selection structure
The if Statement (cont’d.) • In flowchart, diamond represents true/false condition that must be tested • Actions can be conditionally executed • Performed only when a condition is true • Single alternative decision structure: provides only one alternative path of execution • If condition is not true, exit the structure
Nested Decision Structures and the if-elif-else Statement • A decision structure can be nested inside another decision structure • Commonly needed in programs • Example: • Determine if someone qualifies for a loan, they must meet two conditions: • Must earn at least $30,000/year • Must have been employed for at least two years • Check first condition, and if it is true, check second condition
The if-elif-else Statement • if-elif-else statement: special version of a decision structure • Makes logic of nested decision structures simpler to write • Can include multiple elif statements • Syntax: if condition_1: statement(s) elif condition_2: statement(s) Insert as many elif clauses elif condition_3: as necessary. statement(s) else statement(s)
The if-elif-else Statement (cont’d.) • Alignment used with if-elif-else statement: • if, elif, and else clauses are all aligned • Conditionally executed blocks are consistently indented • if-elif-else statement is never required, but logic easier to follow • Can be accomplished by nested if-else • Code can become complex, and indentation can cause problematic long lines
Checking Numeric Ranges with Logical Operators • To determine whether a numeric value is within a specific range of values, use and Example: x >= 10 and x <= 20 • To determine whether a numeric value is outside of a specific range of values, use or Example: x < 10 or x > 20
Boolean Variables • Boolean variable: references one of two values, True or False • Represented by bool data type • Commonly used as flags • Flag: variable that signals when some condition exists in a program • Flag set to False à condition does not exist • Flag set to True à condition exists