Module 4: Selection (Logic)
What is Selection?
Selection means making decisions in code. Your program will choose which path to take based on whether a condition is True or False. We do this using if / elseif / else statements or switch / case statements.
IF Statements
Here is the standard syntax for an IF block in ERL.
- Start with
if [condition] then - Add optional
elseif [condition] then - Add an optional
else - Always close with
endif
ageStr = input("Age?")
age = int(ageStr)
if age >= 18 then
print("You can vote")
elseif age == 17 then
print("You can vote next year")
else
print("Too young to vote")
endif
Exercise: Grade Calculator
Ask the user for their test score (out of 100). Use an IF statement to print out their grade.
- 80 or higher: Grade A
- 60 or higher: Grade B
- 40 or higher: Grade C
- Below 40: Fail
Logical Operators
You can combine conditions using AND and OR. You can reverse a condition with NOT.
if score > 50 AND attendance > 90 then
print("Pass")
endif
Exercise: Weekend Checker
Use input to ask "What day is it?". Use an IF statement with the OR operator to print "Weekend" if the day is "Saturday" or "Sunday". Otherwise print "Weekday".
SWITCH / CASE
When you have many possible exact values for a single variable, switch is cleaner than multiple if/elseif blocks.
switch day:
case "Sat":
print("Weekend!")
case "Sun":
print("Weekend!")
default:
print("Weekday")
endswitch
Exercise: Switch Menu
Ask the user to enter a number (1, 2, or 3). Use a switch statement: if 1 print "New Game", if 2 print "Load Game", if 3 print "Quit", and for default print "Invalid choice".