4. If Statements 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus Have your program make choices. Depending on a test have a program do different things.
If Andrew got the right answer, add 1 point to his score. If Jane hit the alien, make an explosion sound. If the file isn’t there, display an error message. If statement: test, action(s) 2
If Andrew got the right answer, add 1 point to his score. "If" as Rail Lines 3 Test: Did Andrew get the right score? Action: Add 1 point to his score
age1.py 4
print("Enter your age: ", end =" ") age = int(input()) if age > 16: print("You are Old, ") print("Old, " * age) Code Details 5 test: is age > 16? actions must be indented (add 4 spaces at the start of each line)
Test Operations 6
Comparison of Strings Comparison operators work for strings >>> "David" < "David Cameron" True >>> "Dave" < "David" True >>> "Tom" < "Thomas" False >>> "Bill" < "William" True >>> "AAA" < "AAB" True >>> "AAA" < "aaa" True >>> "aaa" < "AAA" False Uses A-Z a-z ordering, letter by letter
8 age2.py
age2.py as Rail Lines 9 age > 16? age >= 12 ? age >= 8 ? Old, old, … Not a bad age Get lost kid Baby
age3.py 10
age3.py as Rail Lines 11 age > 16? Old, old, … age >= 12? age >14 ? Perfect Not a bad age Get lost
The train lines rejoin so Python can execute the next lines of your program. What Happens after the if? 12 more code here
Use the words: and, or, not to build more complex tests: age >= 12 and age <= 14 color == "red" or color == "blue" not name == "Andrew" same as name != "Andrew" These words can be combined to make even more complicated tests: e.g. (name == "Andrew" and age > 18) or (age < 16) Making Complex Tests 13
Complex Test Operations 14 OperatorExampleResult and(2 == 3) and (-1 < 5)False or(2 == 3) or (-1 < 5)True notnot (2 == 3)True
Truth Table for or rate = -1 print rate 100 ABA or B True FalseTrue FalseTrue False Answer?
Truth Table for or rate = 160 print rate 100 ABA or B True FalseTrue FalseTrue False Answer?
Truth Table for or rate = 50 print rate 100 ABA or B True FalseTrue FalseTrue False Answer?
Truth Table for and rate = -1 print rate >= 0 and rate <= 100 ABA and B True False TrueFalse Answer?
Truth Table for and rate = 50 print rate >= 0 and rate <= 100 ABA and B True False TrueFalse Answer?
Truth Table for and rate = 160 print rate >= 0 and rate <= 100 ABA and B True False TrueFalse Answer?
age4.py 21