Selection, Iteration, Logic & Loops.
elif (or else if)elseif/elif/else.
if choice == "A":
print("Add")
elif choice == "S":
print("Subtract")
else:
print("Invalid")
(b) Cleaner code / Easier to read / Optimised by compiler.
(a) 13 (10->15->13)
(b) 15 (Second incorrect condition skipped because first was true)
(a) For Loop: Count-Controlled. We know exact iterations (5).
(b) While Loop: Condition-Controlled. Unknown iterations (depends on user).
(a) num is never changed, so num <= 5 is
ALWAYS valid.
(b) Add num = num + 1 inside loop.
for i in range(8): print(i)
(a) 0, 1, 2, 3, 4, 5, 6, 7 (stops before 8)
(b) for i in range(0, 9, 2): (or range(0, 10, 2))
total printed?
Trace Table:
| i | j | total | Output |
|---|---|---|---|
i=1, j=1..2 (Total +1+1 = 2)
i=2, j=1..2 (Total +2+2 = 6)
i=3, j=1..2 (Total +3+3 = 12)
Final Output: 12
10 (x becomes 7)
7 (x becomes 4)
4 (x becomes 1)
1 (x becomes -2)
Blastoff
valid flag. Use OR/AND and ELSE.
if choice >= 1 and choice <= 3:
# Do nothing or process choice
pass
else:
print("Error")
Also accept: if choice == 1 or choice == 2 or choice == 3:
count = int(input("Students: "))
total = 0
for i in range(count):
score = int(input("Score: "))
if score < 0:
print("Invalid")
else:
total = total + score
print(total / count)
guess = 0
while guess != 7:
guess = int(input("Guess: "))
print("Found it!")