3-2 Decision Operators
3-2 Decision Operators
Section 2
Chapter 3
Decisions (If statement)
EX: test1.py
• The if statement
num = 1
– if condition:
if num>=1:
(tab) statement print('greater')
if num<1:
– condition: logical expression, true or false print('lower')
– logical expression
• 1: true, 0: false, other numbers: true
num = 1
>> 2>0
>> -1>0
– relational operators num >= 1 print('greater')
• < <= ==
• != > >=
• x = 3>2
• x = 3 == 3
• x = 0<0.5<1 num < 1 print(‘lower')
• x != 0, x != 2
Example
• balance = eval(input( 'Enter bank balance
(0~1000): ' ))
• If balance is lower than 500 then compute
the 500-balance & print.
• If balance is higher than 500 then compute
the 1000-balance & print.
• Use the if statement
if-else Statements
EX: test1.py
num = 1
if num>=1:
print('greater')
if num<1:
print('lower')
num = 1
if num>=1:
(else)
num >= 1 print('greater')
else:
print('lower')
print(‘lower') print('greater')
Example
• balance = eval(input( 'Enter bank balance
(0~1000): ' ));
• If balance is lower than 500 then compute
the 500-balance.
• If balance is higher or same than 500 then
compute the 1000-balance.
• Use the if, else statement
Basic form of if-else
• Basic form • elseif ladder
if conditionA: if condition1:
statementsA statementsA
If conditionB: elif condition2:
statementsB statementsB
… elif condition3:
statementsC
…
else:
num = 1 num = 1 statementsE
if num<1: if num<1:
print(‘low') print(‘low')
if 1<num<5: elif num<5:
print(‘middle') print(‘middle')
if num>5: else:
print(‘high') print(‘high')
Example
• balance = eval(input( 'Enter bank balance: (0~1000)' ));
• If balance is lower than 100 then compute the 100-balance.
• If balance is higher than 100 and lower than 300 then compute the 300-bal-
ance.
• If balance is higher than 300 and lower than 500 then compute the 500-bal-
ance.
• If balance is higher than 500 then compute the 1000-balance.
• Use if, elseif, else statment
Logical operators
lex1 lex2 not lex1 lex1 and lex2 lex1 or lex2
• Logical operators F F T F F
– and, or, not
F T T F T
T F F F T
T T F T T
num = 1 num = 1
if num<1: if num<1:
print(‘low') print(‘low')
if 1<num<5: if num>1 and num<5:
print(‘middle') print(‘middle')
if num>5: if num>5:
print(‘high') print(‘high')
Elseif and if
Bank interest rate: <$5000 9%,
$5000≤ and <$10000 12%, ≥$10000 15%
• elseif • if
bal = 15000 * rand bal = 15000 * rand
if bal < 5000: if bal < 5000:
rate = 0.09 rate = 0.09
elif bal < 10000: if bal >= 5000 and bal < 10000:
rate = 0.12 rate = 0.12
else: if bal >= 10000:
rate = 0.15 rate = 0.15