Topics The if Statement The if-else Statement Comparing Strings

Slides:



Advertisements
Similar presentations
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
Python – Making Decisions Lecture 02. Control Structures A program that only has one flow is useful but limited. We can use if statements to make these.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design First Edition by Tony Gaddis.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
INLS 560 – C ONDITIONALS Instructor: Jason Carter.
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
Flow of Control Part 1: Selection
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Decision Structures and Boolean Variables. Sequence Structures Thus far, we’ve been programming “sequence structures” Thus far, we’ve been programming.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Decision Making CMSC 201 Chang (rev ).
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Introduction to Decision Structures and Boolean Variables
Control Structures I Chapter 3
Java Programming Fifth Edition
The if…else Selection Statement
More on the Selection Structure
Chapter 2: Input, Processing, and Output
Selection and Python Syntax
Chapter 4: Making Decisions.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
The Selection Structure
Topics The if Statement The if-else Statement Comparing Strings
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 4: Decision Structures and Boolean Logic
Chapter 4: Making Decisions.
Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Javascript Conditionals.
Making Decisions in a Program
Topics The if Statement The if-else Statement Comparing Strings
And now for something completely different . . .
Chapter 3:Decision Structures
Chapter 4: Decision Structures and Boolean Logic
Introduction to Programming
3. Decision Structures Rocky K. C. Chang 19 September 2018
Selection Statements.
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and.
Introduction to Decision Structures and Boolean Variables
Logical Operators Operators that can be used to create complex Boolean expressions and or not.
The if Statement Control structure: logical design that controls order in which set of statements execute Sequence structure: set of statements that execute.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
Chapter 2: Input, Processing, and Output
Chapter 4: Selection Structures: if and switch Statements
Control Statements.
Introduction to Programming
Chapter 4: Decision Structures and Boolean Logic
Flow Control I Branching and Looping.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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!')

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

if-else Statement Flow Chart

The if-else Statement Flow

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

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='')

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

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

Comparing Strings

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

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

Nesting Flow Chart

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.') print('You must earn at least $', \ format(MIN_SALARY, ',.2f'), ' per year to qualify.', sep='')

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

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.

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