1 / 33

Topics

Topics. The if Statement The if-else Statement Comparing Strings Nested Decision Structures and the if-elif-else Statement. Boolean Values. Boolean Values can only be one of only two values True False. If/Else Decision Structure.

lbingham
Download Presentation

Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topics • The if Statement • The if-else Statement • Comparing Strings • Nested Decision Structures and the if-elif-else Statement

  2. Boolean Values • Boolean Values can only be one of only two values • True • False

  3. 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

  4. 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

  5. Python Structures • Control structure: logical design that controls the order of how a set of Python 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 a selection structure

  6. 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

  7. The if Statement Flowchart • Single alternative decision structure • Provides only one alternative path of execution • If condition is not true, exit the structure

  8. The if Statement Syntax • Python syntax: if condition: Statement 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 the block is finished • Otherwise, block statements are skipped

  9. Relational Operators • 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

  10. Boolean Expressions • Boolean expression: an expression tested by the 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

  11. Boolean Expressions • == operator determines whether the two operands are equal to one another • Do not confuse with assignment operator (=)

  12. Boolean Expression in Flow Chart • Using a Boolean expression with the > relational operator

  13. 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

  14. 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

  15. 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: ')) # notice that answer is test2 = int(input('Enter the score for test 2: ')) # converted to integer 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: # notice : at end of if statement print('Congratulations!') # notice indentation print('That is a great average!') # same indentation and end of block

  16. 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

  17. if-else Statement Flow Chart

  18. The if-else Statement Flow

  19. 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

  20. 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: ')) # convert to float # 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='')

  21. 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

  22. Example name1 = 'Mary' name2 = 'Mark' if name1 > name2: print(name1, ">", name2) else: print(name2, '>', name1) Output Mary > Mark

  23. Comparing Strings

  24. 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.')

  25. Nested if-else Statement • Sometimes a decision needs to be made after a previous 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

  26. Nesting Flow Chart

  27. Program # This program determines whether a bank customer qualifies for a loan. MIN_SALARY = 30000.0 # 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.') else: print('You must earn at least $', \ format(MIN_SALARY, ',.2f'), ' per year to qualify.', sep='')

  28. Nested if-else StatementIndentation • Important to use proper indentation in a nested decision structure • Important for Python interpreter • Will complain about indentation • 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

  29. The if-elif-else Statement • Special version of a decision structure • Uses elifinstead 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: statement(s) elif condition_3: statement(s) else statement(s) Insert as many elif clauses as necessary.

  30. Program grade = int(input("what is the grade?")) if grade >= 90: print("you get an A") elif grade >= 80: print("you get a B") elif grade >= 70: print("you get a C") elif grade >= 60: print("you get a D") else: print("you get a F")

  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

More Related