0% found this document useful (0 votes)
34 views28 pages

07-Python 3

Here is a program to solve this problem: packages = int(input('Enter number of packages purchased: ')) original_price = 99 if packages >= 10: discount = original_price * 0.25 print('Discount amount is $', discount) elif packages >= 6: discount = original_price * 0.20 print('Discount amount is $', discount) elif packages >= 3: discount = original_price * 0.10 print('Discount amount is $', discount) else: discount = 0 total = packages * original_price - discount print('Total amount due is $', total)

Uploaded by

maha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views28 pages

07-Python 3

Here is a program to solve this problem: packages = int(input('Enter number of packages purchased: ')) original_price = 99 if packages >= 10: discount = original_price * 0.25 print('Discount amount is $', discount) elif packages >= 6: discount = original_price * 0.20 print('Discount amount is $', discount) elif packages >= 3: discount = original_price * 0.10 print('Discount amount is $', discount) else: discount = 0 total = packages * original_price - discount print('Total amount due is $', total)

Uploaded by

maha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

UNIT 3

Decision Structures and Boolean


Logic
Decision structure
Sequence structure: set of statements that execute in the
order they appear
All previous programs were in sequence structure

Assume we want to read three grades and


display “Fail” if the average is less than 60, and
display “Pass” if the average is greater than or
equal 60.

Decision structure: specific action(s) performed only if a


condition exists
To form a condition, we need to use relational operators
Relational Operators
• Relational operators are used to compare elements (numbers
or chars) to determine relative order.
• These operators are:
Relational Expressions
• The value of a relational expression is either true or false.
• Examples:
12 > 5 true
7 <= 5 false
if x is 10 and y is 7, then
x == 10 true
x != y true
x == 8 false
x < y + 1 false

Do not confuse between “=“ (assignment) and “==“ (equal to)


The if Statement
• The if statement is a control structure: it allows to control the
execution of the program by allowing statements to be
conditionally executed or skipped over.
• It models the way we mentally evaluate situations
“If it is cold outside,
wear a coat, wear a hat, wear gloves”
If condition is
condition false,
then the
If condition is statement(s)
true, then the are skipped.
statement(s)
in the body are
executed. 1 or more
statements
if Statement Flow of Control
Print “Enter
your grade”
if condition:
Read grade statement1
statement2
No … body
Grade>=90 statementn
Yes

Print
grade=int(input('Enter your grade '))
“Congratulations!”
if grade >=90:
print('Congratulations!')
Print “Great grade!” print(‘Great grade!')
print('Your grade is ',grade)

Print “your grade


is, grade”
if Statement Notes
• Do not forget to place: after (condition)

• Increase indent after an if statement, to indicate the


scope of the block (which lines are affected by the if)
• Reduce indent back to the level of the if statement to
indicate the end of the block
The if/else Statement
Dual alternative decision structure: two possible paths of
execution
Allows a choice between statements depending on whether
(condition) is true or false
if condition:
Statement
Statement
..etc
else:
Statement
Statement
..etc

if clause and else clause must be aligned


If/else Statement Flow of Control
if score >= 60:
print("Passed.")
else:
print("Failed.")
Exercises :
x=int(input('Enter a number '))
if x>0:
print('positive')
else:
print('negative')
What is the output if user enters zero?!

Write a program to read two integer numbers and


display the maximum one.

Write a program to read a number and display if it


is odd or even
Exercises :
Write a program to read a salary of employee and
deduct 10% tax if the salary is less than 10,000, and
15% if the salary is 10,000 or more. Your program
should display the net salary.
Nested Decision Structure
• If/else works when we have only two choices, but there are
many cases when we have more than two choices. For
example, we want to read a number from user and decide if it
is zero, positive, or negative.
Nested Decision Structure
x=int(input('Enter a number '))
if x==0:
print("Zero")
else:
if x>0:
print('positive')
else:
print('negative')
Nested Decision Structure
• Write a program to read a score,
and print the corresponding letter
grade according to the following
score = int(input('Enter your test score: '))
# Determine the grade.
if score >= 90:
print('Your grade is A.')
else:
if score >= 80:
print('Your grade is B.')
else:
if score >=70:
print('Your grade is C.')
else:
if score >=60:
print('Your grade is D.')
else:
print('Your grade is F.')
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)
score = int(input('Enter your test score: '))
if score >= 90:
print('Your grade is A.')
elif score >= 80:
print('Your grade is B.')
elif score >= 70:
print('Your grade is C.')
elif score >= 60:
print('Your grade is D.')
else:
print('Your grade is F.')
Logical Operators
• Logical operators: operators that can be used to
create complex Boolean expressions
• and operator and or operator: binary operators,
connect two Boolean expressions into a compound
Boolean expression
• not operator: unary operator, reverses the truth of its
Boolean operand
The and Operator
• Takes two Boolean expressions as operands
• Creates compound Boolean expression that is true only
when both sub expressions are true
• Can be used to simplify nested decision structures
• Truth table for Expression Value of the
Expression
the and operator false and false false
false and true false
true and false false
true and true true
The or Operator
• Takes two Boolean expressions as operands
• Creates compound Boolean expression that is true when either of
the sub expressions is true
• Can be used to simplify nested decision structures
• Truth table for Expression Value of the
Expression
the or operator false or false false
false or true true
true or false true
true or true true
Short-Circuit Evaluation
• Short circuit evaluation: deciding the value of a compound
Boolean expression after evaluating only one sub
expression
• Performed by the or and and operators
• For or operator: If left operand is true, compound expression is true.
Otherwise, evaluate right operand
• For and operator: If left operand is false, compound expression is false.
Otherwise, evaluate right operand
The not Operator
• Takes one Boolean expressions as operand and reverses
its logical value
• Sometimes it may be necessary to place parentheses around an
expression to clarify to what you are applying the not operator
• Truth table for the not operator

Expression Value of the Expression


true false
false true
Logical Operator Examples

• x = 12, y = 5, z = -4;
(x > y) and (y > z) true

(x > y) and (z > y) false


(x <= z) or (y == z) false
(x <= z) or (y != z) true
not(x >= z) false
Logical Precedence
Precedence Operator
Highest not
and
Lowest or

Example:

(2 < 3) or (5 > 6) and (7 > 8)

is true because AND is evaluated before OR


Checking Numeric Ranges
• Used to test if a value is within a range
if grade >= 0 and grade <= 100:
print("Valid grade")

• Can also test if a value lies outside a range


if grade < 0 or grade > 100:
print("Invalid grade")
• Cannot use mathematical notation
if 0<=grade<=100: # works!
# it is equivalent to:
if 0<=grade and grade<=100:
Validating User Input
• Input validation: inspecting input data to determine if
it is acceptable
• Want to avoid accepting bad input
• Can perform various tests. Examples:
• Range
• Valid menu choice
• Zero as a divisor
if(score < 0 or score > 100):
print('invalid score')
Exercise :
• Write a program to read three integer numbers and
print the maximum.
Exercise
• A software company sells a package that retails for $99.
• Quantity discounts are given according to the following
table:

• Write a program that asks the user to enter the number of


packages purchased. The program should then display
the amount of the discount (if any) and the total amount of
the purchase after the discount.

You might also like