SlideShare a Scribd company logo
1 of 33
C H A P T E R 3
Decision
Structures
and Boolean
Logic
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 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
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
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
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
Operator Meaning
= = Equal to
! = Not equal to
> Greater than
> = Greater than or
equal to
< Less than
< = Less than or
equal to
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
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: ')) # 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
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: ')) # 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='')
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 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
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.')
else:
print('You must earn at least $', 
format(MIN_SALARY, ',.2f'), ' per year to qualify.', sep='')
Nested if-else Statement
Indentation
◦ 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
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:
statement(s)
elif condition_3:
statement(s)
else
statement(s)
Insert as many elif clauses
as necessary.
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")
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 Content

What's hot

Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and DictionaryAswini Dharmaraj
 
python conditional statement.pptx
python conditional statement.pptxpython conditional statement.pptx
python conditional statement.pptxDolchandra
 
Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & ExceptionsOmid AmirGhiasvand
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programmingSrinivas Narasegouda
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D arraySangani Ankur
 
Python data type
Python data typePython data type
Python data typenuripatidar
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 

What's hot (20)

Python for loop
Python for loopPython for loop
Python for loop
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
python conditional statement.pptx
python conditional statement.pptxpython conditional statement.pptx
python conditional statement.pptx
 
Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & Exceptions
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
List in Python
List in PythonList in Python
List in Python
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Interface
InterfaceInterface
Interface
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
 
Functions in python
Functions in python Functions in python
Functions in python
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
Python data type
Python data typePython data type
Python data type
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Strings
StringsStrings
Strings
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 

Similar to Decision Structures and Boolean Logic

Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and SelectionAhmed Nobi
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptxrani marri
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Decision Controls in C++ Programming Lecture
Decision Controls in C++ Programming LectureDecision Controls in C++ Programming Lecture
Decision Controls in C++ Programming LectureTishaFayeMendoza
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleumaghosal12101974
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
Lec16.pptx problem specifications computer
Lec16.pptx problem specifications computerLec16.pptx problem specifications computer
Lec16.pptx problem specifications computersamiullahamjad06
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.pptTekle12
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 

Similar to Decision Structures and Boolean Logic (20)

Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Decision Controls in C++ Programming Lecture
Decision Controls in C++ Programming LectureDecision Controls in C++ Programming Lecture
Decision Controls in C++ Programming Lecture
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Fekra c++ Course #2
Fekra c++ Course #2Fekra c++ Course #2
Fekra c++ Course #2
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment example
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lec16.pptx problem specifications computer
Lec16.pptx problem specifications computerLec16.pptx problem specifications computer
Lec16.pptx problem specifications computer
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.ppt
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 

More from Munazza-Mah-Jabeen (20)

Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
The Standard Template Library
The Standard Template LibraryThe Standard Template Library
The Standard Template Library
 
Object-Oriented Software
Object-Oriented SoftwareObject-Oriented Software
Object-Oriented Software
 
Templates and Exceptions
 Templates and Exceptions Templates and Exceptions
Templates and Exceptions
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
More About Strings
More About StringsMore About Strings
More About Strings
 
Streams and Files
Streams and FilesStreams and Files
Streams and Files
 
Lists and Tuples
Lists and TuplesLists and Tuples
Lists and Tuples
 
Files and Exceptions
Files and ExceptionsFiles and Exceptions
Files and Exceptions
 
Functions
FunctionsFunctions
Functions
 
Pointers
PointersPointers
Pointers
 
Repitition Structure
Repitition StructureRepitition Structure
Repitition Structure
 
Inheritance
InheritanceInheritance
Inheritance
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Arrays and Strings
Arrays and StringsArrays and Strings
Arrays and Strings
 
Objects and Classes
Objects and ClassesObjects and Classes
Objects and Classes
 
Functions
FunctionsFunctions
Functions
 
Structures
StructuresStructures
Structures
 
Loops and Decisions
Loops and DecisionsLoops and Decisions
Loops and Decisions
 

Recently uploaded

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 

Recently uploaded (20)

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 

Decision Structures and Boolean Logic

  • 1. C H A P T E R 3 Decision Structures and Boolean Logic
  • 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 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
  • 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 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
  • 10. 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 Operator Meaning = = Equal to ! = Not equal to > Greater than > = Greater than or equal to < Less than < = Less than or equal to
  • 11. 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
  • 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: ')) # 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
  • 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
  • 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: ')) # 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='')
  • 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
  • 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 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
  • 28. 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='')
  • 29. Nested if-else Statement Indentation ◦ 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
  • 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: statement(s) elif condition_3: statement(s) else statement(s) Insert as many elif clauses as necessary.
  • 31.
  • 32. 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")
  • 33. 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