Selection and conditionals
مُقدَّم| English | المعنى |
|---|---|
| condition/kənˈdɪʃn/ | شرط |
| selection/sɪˈlekʃn/ | اختيار |
Why did the pensioner pay the student price?
- A cinema charges £5 for children and over-65s, £7 for students and £10 for everyone else. A 70-year-old student was charged £7.
- Every rule in the program was correct. The rules were simply tested in the wrong order. This lesson is about how a program chooses a road, and why order is part of the design.
A condition is a True or False question
- A condition 条件 is an expression whose value is a
bool:age >= 65,answer == "y",n != 0. The comparisons are<,<=,>,>=,==(equal) and!=(not equal). - Join conditions with
and(both must be true),or(at least one) andnot(flips it).3 >= 3 and not (2 > 5)isTrue.
student = input("Student? y/n ") == "y" # already a bool
print(type(student)) # <class 'bool'>
What does print(3 >= 3 and not (2 > 5)) show?
الصعوبة 1/5 · 100 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
3 >= 3 is True; 2 > 5 is False, so not (2 > 5) is True. Both sides are true, so and gives True.
if and else: one of two roads
if condition:runs the indented block only when the condition isTrue. Anelse:block runs when it isFalse. Exactly one of the two runs.- The indentation is the block. Lines indented under
ifbelong to it; the first line back at the left edge runs whatever happened.
if total >= 50:
fee = 0
else:
fee = 5
print("Delivery:", fee) # always runs
A line that is not indented, written straight after an if block, runs only when the condition is True.
الصعوبة 1/5 · 100 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Only indented lines belong to the if. The first line back at the left edge is outside the block, so it runs either way.
elif: the first true branch wins
- Selection 选择 with
if … elif … elsetests the conditions from top to bottom and runs only the first one that isTrue. All the others are skipped, even if they are also true. elsecatches whatever is left, so a full chain always takes exactly one road.

A shop uses if total >= 50: fee = 0, then elif total >= 20: fee = 3, then else: fee = 5. What is fee when total is exactly 20?
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
20 >= 50 is False, so the chain moves on; 20 >= 20 is True, so fee = 3 runs and the else is skipped. A boundary value is exactly the case worth testing.
Trust the fall-through
- An
elifis only reached when every test above it has failed. Soelif score >= 70does not needand score < 80: reaching that line already proves the score is below 80. - Writing the extra test is longer, and each copy is one more place to make a mistake at the boundary.
if score >= 80:
band = "A"
elif score >= 70: # here score < 80 is already known
band = "B"
elif score >= 60:
band = "C"
else:
band = "F"
أي الفرعين يتم تنفيذه؟
Drag the score and watch the chain test each condition from the top. Only the first true branch runs; at 79 the test score >= 80 fails and score >= 70 wins.
In the band chain, why does elif score >= 70: not need and score < 80?
الصعوبة 1/5 · 100 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
كل elif inherits the failure of every test above it. A score of 80 or more has already been caught by the first branch.
Put the narrow rule first
- When two rules can both be true, the one written first decides. Put the rule that must win, usually the narrower one, above the wider one.
- Test one input from each road, and one input that matches two rules. That overlap case is where order bugs hide.
- Children and over-65s pay £5, students £7, others £10.
- Age first:
if age < 12 or age >= 65:thenelif student:thenelse:. A 70-year-old student pays £5. - Student first: the same person hits
if student:and pays £7. Both programs pass a test with a 20-year-old student (£7) and a 30-year-old (£10). Only the overlap case shows the difference.
Put the lines in order so that a 70-year-old student pays £5 and a 20-year-old student pays £7.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
The age rule must win the overlap case, so it is tested first. A 20-year-old student fails the age test and reaches elif student:.
Combine conditions with care
- Python lets you chain comparisons:
0 <= mark <= 100means0 <= mark and mark <= 100. andstops as soon as the answer is known.n != 0 and total / n > 5never divides by zero, because whennis0the left side is alreadyFalse.
Let x = 15. Which conditions are True? Select all that apply.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
The chain holds, and $15$ is a multiple of 5. not x > 10 is False. The last one is the trap: it means (x == 10) or 20, and 20 counts as true, so it is true for every x.
Marks that slip away
=in a condition.if x = 5:is a syntax error; comparing needs==.x == 1 or 2. This means(x == 1) or 2, and2counts as true, so the test is always true. Writex == 1 or x == 2, orx in (1, 2).- Separate
ifs where you meantelif. Three separateifstatements can all run; anelifchain runs one. - Boundaries.
>or>=? Test the exact boundary value, such as a score of exactly 70.
A program has three separate statements: if score >= 60: print("C"), if score >= 70: print("B"), if score >= 80: print("A"). What does it print for a score of 85?
الصعوبة 1/5 · 100 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
الفصل if statements are each tested, so all three run. An if … elif chain with the highest band first would print only A.
You've got it
- A condition is a
boolexpression; build it from comparisons withand,orandnot. if … elif … elsetests from the top and runs only the first true branch;elsetakes what is left.- Each
elifalready knows that the tests above it failed. Order is design: put the rule that must win first, and test the overlap and boundary cases.