Decisions Structures:
if, elif, else &
boolean logic
Lawrence Blake Jones | lbjones@unc.edu | INLS 560
INLS 161
Tools for
Information
Literacy
Python can make decisions when executing code based on the logic you add to a script.
The logic you add determines what should happen if the code encounters a situation that is either True or False.
In Python, the situation is called a condition.
sales = 60000
bonus = 500
if sales > 50000:
print(f"Woo-hoo! you got a bonus of ${bonus}")
The if statement is for
logical & conditional decisions that evaluate as either
True or False
statement following if
is a conditional
indentation
is REQUIRED
code block
the entire first line is called the if clause:
if sales > 50000:
colon is REQUIRED
Woo-hoo! you got a bonus of $500
The condition is true, so the print function is executed.
you can have multiple statements; all must be indented same as first line
sales = 1000
years_service = 4
bonus = 500
if sales > 50000:
print(f"You meet the sales requirement.")
if years_service > 2:
print(f"You meet the years of service requirement.")
You meet the years of service requirement.
If you use multiple if statements:
only True conditions will execute
False so will not print.
True
True so will print.
sales = 1000
bonus = 500
if sales > 50000:
print(f"Woo-hoo! you got a bonus of ${bonus}")
Let's go back to the first example:
What if the ONLY condition evaluates as
False ?
The condition is false, so nothing is printed
Process finished with exit code 0
Or you might get a warning message:
This is where adding an else is helpful. See the next slide.
These are poor user experiences.
sales = 1000
bonus = 500
if sales > 50000:
print(f"Woo-hoo! you got a bonus of ${bonus}")
else:
print("You did not get the bonus.")
you did not get the bonus.=
if the condition can evaluate as
False
add an else
The condition is false, so the else is printed
Adding an else looks like this:
Your if else script can contain one condition…
if
else
Or your if script can contain many else conditions all with their own set of actions.
if
elif
elif
elif
elif
elif
elif
elif
else
Use else only once, as the fallback for all unmatched conditions.
Use elif for testing multiple different conditions.
Use elif for testing multiple different conditions.
Use elif for testing multiple different conditions.
Again, a final else is not required for syntax: the code will run. But it may result in a poor user experience.
if
else
Example Code for one if else condition:
direction = input("Which direction do you want to go? (NW or NE): ")
if direction == "NW":
print("Person walks Northwest.")
else:
print("Person walks. Northeast.")
The programmer has not made this program very "robust". We will see why in a few slides.
Notice this symbol which means equals: ==
The exact equal symbol does not mean equals in the mathematical sense. It is known as an assignment operator which means equals: =
In the previous program there was only one condition* that could be be true or false.
And the user must choose NW or NE.
If a user enters "s" or even "nw" (lower case):
the output will be:
Which direction do you want to go? (NW or NE): nw
Person walks Northeast. # ONLY capital NW will return true.
*Don't confuse condition with choice.
Conditions must be true or false.
So every condition must have at least two choices.
direction = input("Which direction do you want to go? (N, E, S, W, NE, NW, SE, SW): ").strip().upper()
if direction == "N":
print("Person walks North.")
elif direction == "E":
print("Person walks East.")
elif direction == "S":
print("Person walks South.")
elif direction == "W":
print("Person walks West.")
elif direction == "NE":
print("Person walks Northeast.")
elif direction == "NW":
print("Person walks Northwest.")
elif direction == "SE":
print("Person walks Southeast.")
elif direction == "SW":
print("Person walks Southwest.")
else:
print("Unknown direction. Person stays put.")
direction = input("Which direction do you want to go? (N, E, S, W, NE, NW, SE, SW): ").strip().upper()
if direction == "N":
print("Person walks North.")
elif direction == "E":
print("Person walks East.")
elif direction == "S":
print("Person walks South.")
elif direction == "W":
print("Person walks West.")
elif direction == "NE":
print("Person walks Northeast.")
elif direction == "NW":
print("Person walks Northwest.")
elif direction == "SE":
print("Person walks Southeast.")
elif direction == "SW":
print("Person walks Southwest.")
else:
print("Unknown direction. Person stays put.")
This else and print statement could be removed and the program would run without an error.
But it is good for giving feedback if someone enters any other choice besides
N, E, S, W, NE, NW, SE, SW
Methods allow for user input formatting or validation. Validation and formatting are critical steps in collecting user input or collecting data.
x = 5
if x > 2: # true so continues
x = -3 # x is now assigned value of -3
elif x > 1: # false, so testing is over;
x = 1 # testing is over
else: # testing is over
x = 3 # testing is over
print(x)
x = 5
if x > 2: # true so continues
x = -3 # x is now assigned value of -3
if x > 1: # false, but continues; x is still -3
x = 1 # does execute because prior line is false
else: # true and is last test so is true
x = 3 # final else is a catch all, so it changes x to 3
print(x)
3
-3
if and else statements continue…
elif statements are a hard stop
elif is a hard stop test
Code below for both blocks is exactly the same except for the if and the elif in black
if/else tests are not hard stop tests; testing continues
age = int(input("Enter your age: "))
if age < 4:
print("Admission is free!")
elif age < 18:
print("Admission is $25.")
elif age > 60:
print("Admission is $35.")
elif age >= 100:
print("Admission is free!")
else:
print("Admission is $40.")
Enter your age: 102
Admission is $35.
Be careful to test your elif statements.
A centenarian aged 102 should get into the amusement park free of charge:
It is true that age 102 is greater than 60
It is also true that an elif statement is a hard stop.
So this executes before we get to the age >100 condition
Centenarian does not get free admission.
Solution is to move the elif statement and block above 60
Control Structures
INPUT/output
symbol
Terminal Symbol (start)
Processing Symbol
Terminal Symbol (end)
input/OUTPUT
symbol
INPUT/output
symbol
Condition Test if clause
if Condition:
True
Sequence Structure
Decision Structure
False
Processing Symbol
if condition:
statement
statement
indent
block
statement
statement
Relational Operators AKA Comparison Operators
Operator | Meaning |
> | Greater That |
< | Less Than |
>= | Greater than or equal to |
<= | Less than or equal to |
== | Equal to |
!= | Not equal to |
Boolean Expression using Relational Operators
x = 1
y = 0
x > y
True
y > x
False
x == y + 1
True
Is y greater than x?
Is x greater than y?
Experiment with these expressions with Python in Interactive mode
Is x equal to y + 1? (==)
1
2
3
4
5
6
7
8
IMPORTANT:
= is used as an assignment operator as in line 1 and 2
equals is == as is shown in line 7
loan_qualifier.py
# customer loan qualification program
MIN_SALARY = 30000.0 # Minimum salary
MIN_YEARS = 2 # Minimum years on job
# Get annual salary.
salary = float(input('Enter annual salary: '))
# Get years on job.
years_on_job = int(input('Enter years employed: '))
# Does customer qualify?
if salary >= MIN_SALARY:
if years_on_job >= MIN_YEARS:
print('yes loan')
else:
print('no loan')
else:
print('no loan')
# Does customer qualify?
if salary >= MIN_SALARY and years_on_job >= MIN_YEARS:
print('yes loan')
else:
print('no loan')
loan qualifier.py variables and input are the same
loan qualifier2.py
nested decision structure
the and operator can simplify nested decision structures.
*comments simplified to reduce
cognitive load :)
loan qualifier2.py
strings simplified and comments removed to increase focus on code
MIN_SALARY = 30000.0
MIN_YEARS = 2
salary = float(input('Enter annual salary: '))
years_on_job = int(input('Enter years employed: '))
if salary >= MIN_SALARY and years_on_job >= MIN_YEARS:
print('yes loan')
else:
print('no loan')
MIN_SALARY = 30000.0
MIN_YEARS = 2
salary = float(input('Enter annual salary: '))
years_on_job = int(input('Enter years employed: '))
if salary >= MIN_SALARY or years_on_job >= MIN_YEARS:
print('yes loan')
else:
print('no loan')
must meet both conditions
can meet either condition (less restrictive)
loan qualifier3.py
same as previous page
the and operator can simplify nested decision structures.
all is the same as loan qualifier 2, but the and is changed to or
>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>>
Keywords we have learned since beginning the class:
# Create two or three constants for user input comparison.
CONSTANT_1 = value
CONSTANT_2 = value
# Create two or three variables for provided data
# var1 = int(input()) # if you use an integer
# var2 = str(input()) # str is not required if you use text
# write if statement with and (ok to use or if appropriate)
# if var1 >= CONSTANT_1 and var2 >= CONSTANT_2 :
# print("True response")
# else:
# print(f'''False response
You need {CONSTANT_1} Constant one details and {CONSTANT_2}
details.
''')
Example Code
main.py assignment three
Enter your years of experience driving: 3
Enter how many accidents you have been in: 5
Congratulations! You are eligible for a loan.
Enter your age: 20
Are you a resident of Orange County? Y or N: y
You are not eligible to vote in Orange County.
In order to vote, you must:
- Be at least 18 years of age
- Be registered to vote in that same county
Enter how your completed class hours here: 45
Enter how many capstone projects you have completed: 3
Enter how many times you have passed the comp exam: 0
I am sorry, you do not meet the requirements to graduate.
You need at least
-48 academic hours completed as a SILS student.
-1 thesis or practicum completed.
-1 passing grade for the comprehensive exam.
Please go to the UNC SILS website to see the course list.
Enter how your completed class hours here: 48
Enter how many capstone projects you have completed: 1
Enter how many times you have passed the comp exam: 1
Congratulations! You are ready to graduate!
Voter Eligibility
Constants for UNC SILS graduation requirements
Driving Experience
Student Examples from previous Semesters
?
?
?
# Create two or three constants for user input comparison.
CONSTANT_1 = value
CONSTANT_2 = value
# Create two or three variables for provided data
# var1 = int(input()) # if you use an integer
# var2 = str(input()) # str is not required if you use text
# write if statement with and (ok to use or if appropriate)
# if var1 >= CONSTANT_1 and var2 >= CONSTANT_2 :
# print("True response")
# else:
# print(f'''False response
You need {CONSTANT_1} Constant one details and {CONSTANT_2}
details.
''')
main.py
After you finish your code and have tested it for both True and False responses, and have made sure you don't have any logical errors, upload it to assignment_03 folder.
Next sesion
Repetition
(loops)