Download presentation
Presentation is loading. Please wait.
Published byBambang Halim Modified over 5 years ago
2
Topics The if Statement The if-else Statement Comparing Strings
Nested Decision Structures and the if-elif-else Statement
3
Boolean Values Boolean Values can only be one of only two values True
False
4
If/Else Decision Structure
All previous instructions have been consecutively executed One After The Other If/Else checks a Boolean condition then makes a decision If condition is True: one set of instructions are executed False: a different set of instructions is executed
5
The if Statement All previous instructions have been consecutively executed One After The Other If statement makes a decision If a Boolean expression or condition is True: one set of instructions are executed False: a different set of instructions is executed
6
Python Structures 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
7
The if Statement 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
8
The if Statement Flowchart
Single alternative decision structure Provides only one alternative path of execution If condition is not true, exit the structure
9
The if Statement Syntax
Python syntax: if condition: Statement if statement Includes the keyword if followed by a Boolean condition The condition can be true or false Condition has to be followed by a colon like above When the if statement executes, the condition is tested If it is true the subsequent indented statements (called block statements) are executed Indentation is required to tell Python when block is finished Otherwise, block statements are skipped
10
Relational Operators Operator Meaning = = Equal to ! = Not equal to
> Greater than > = Greater than or equal to < Less than < = Less than or equal to Used to compare values and determine whether relationships exist Greater than Less than Equal to Compare two values and determine how they relate to each other
11
Boolean Expressions Boolean expression: an expression tested by if statement to determine if it is true or false Example: a > b true if a is greater than b; false otherwise > is the relationship a > b is an expression
12
Boolean Expressions == operator determines whether the two operands are equal to one another Do not confuse with assignment operator (=)
13
Boolean Expression in Flow Chart
Using a Boolean expression with the > relational operator
14
Example Science teacher gives three tests
Wants to write a program that averages test scores Wants to congratulate students if average is great than 95
15
Example Pseudocode/algorithm
Get the first test score Get the second test score Get the third test score Calculate the average Display the average If average is > 95 Congratulate the user
16
Program # This program gets three test scores and displays their average. # It congratulates the user if the # average is a high score. high_score = 95 # Get the three test scores. test1 = int(input('Enter the score for test 1: ')) test2 = int(input('Enter the score for test 2: ')) test3 = int(input('Enter the score for test 3: ')) # Calculate the average test score. average = (test1 + test2 + test3) / 3 # Print the average. print('The average score is', average) # If the average is a high score, congratulate the user. if average >= high_score: print('Congratulations!') print('That is a great average!')
17
The if-else Statement Dual alternative decision structure: two possible paths of execution One is taken if the condition is true, and the other if the condition is false Syntax: if condition: statements else: other statements if clause and else clause must be aligned Statements must be consistently indented
18
if-else Statement Flow Chart
19
The if-else Statement Flow
20
Example Auto repair business wants a payroll program to pay overtime when an employee works > 40 hours Pseudocode/algorithm Get the number of hours worked Get the hourly pay rate If employee worked more than 40 hours Calculate and display pay with overtime Else Calculate and display pay as usual
21
Program # Variables to represent the base hours and the overtime multiplier. base_hours = 40 # Base hours per week ot_multiplier = 1.5 # Overtime multiplier # Get the hours worked and the hourly pay rate. hours = float(input('Enter the number of hours worked: ')) pay_rate = float(input('Enter the hourly pay rate: ')) # Calculate and display the gross pay. if hours > base_hours: overtime_hours = hours - base_hours overtime_pay = overtime_hours * pay_rate * ot_multiplier gross_pay = base_hours * pay_rate + overtime_pay else: gross_pay = hours * pay_rate # Display the gross pay. print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
22
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, <, >=, and <= Compared character by character based on the ASCII values for each character If shorter word is substring of longer word, longer word is greater than shorter word
23
Example name1 = 'Mary' name2 = 'Mark' if name1 > name2: print(name1, ">", name2) else: print(name2, '>', name1) Output Mary > Mark
24
Comparing Strings
25
Example # This program compares two strings. # Get a password from the user. password = input('Enter the password: ') # Determine whether the correct password # was entered. if password == 'prospero': print('Password accepted.') else: print('Sorry, that is the wrong password.')
26
Nested if-else Statement
Sometimes a decision needs to be made after another decision was made Called nesting 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
27
Nesting Flow Chart
28
Program # This program determines whether a bank customer qualifies for a loan. MIN_SALARY = # The minimum annual salary MIN_YEARS = 2 # The minimum years on the job salary = float(input('Enter your annual salary: ')) years_on_job = int(input('Enter the number of ' + 'years employed: ')) if salary >= MIN_SALARY: # Determine whether the customer qualifies. if years_on_job >= MIN_YEARS: print('You qualify for the loan.') else: print('You must have been employed', \ 'for at least', MIN_YEARS, 'years to qualify.') print('You must earn at least $', \ format(MIN_SALARY, ',.2f'), ' per year to qualify.', sep='')
29
Nested if-else Statement
Important to use proper indentation in a nested decision structure Important for Python interpreter Makes code more readable for programmer Rules for writing nested if statements else clause should align with matching if clause Statements in each block must be consistently indented
30
The if-elif-else Statement
Special version of a decision structure Uses elif instead of multiple nested elses Makes logic of nested decision structures simpler to write Can include multiple elif statements Syntax: if condition_1: statement(s) elif condition_2: elif condition_3: else Insert as many elif clauses as necessary.
31
The if-elif-else Statement
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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.