Python - 4. Conditionals (If...Else)
4.2 The if Statement (A4.1 - A4.2)
4.6 Logical Operators (and / or) (A4.8)
4.9 if Statements and Functions
CH. 4 PROJECT: Choose your own adventure
4. If...else
4.1 Conditions
- The following are called logical conditions and give a result of True or False (a boolean):
Equals: a == b
Not Equals: a != b (exclamation point represents “not”)
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example #1:
print(20 < 5)
OUTPUT: False
In this small Python program the logical condition 20 < 5 is evaluated as False. That boolean value is then printed to the screen.
Example #2:
a = 7
b = 4
print(a != b)
OUTPUT: True
In this program, with a as 7 and b as 4, a != b is a True statement. True is printed to the screen.
4.2 The if Statement (A4.1 - A4.2)
- You can have a program do something “if” a condition is True, or do something else “if” that condition is False. This is the first time that a program is not running completely linearly (in a line). Here, the logic in an if statement allows different paths for the program to take depending on the conditions. The computer can make a decision on how to proceed. This is called control flow.
- The syntax (way things are written) of an if statement in Python uses a colon and indentation like our functions did.
Example #3:
a = 77
b = 1000
if b > a:
print("b is greater than a")
OUTPUT: b is greater than a
In this example, the variables a and b are used in the if statement to test whether b is greater than a. This is True, so the print statement is executed (carried out). Notice the colon at the end of the first line with the if in it and the indentation of the line following it.
Example #4:
When the if statement results in False, the rest of the indentation is skipped and the program continues after the if block.
a = 77
b = 1000
if b < a:
print(“b is less than a”)
print(“This is the end of the program!”)
OUTPUT: This is the end of the program!
4.3 Else (A4.3 - A4.5)
- The else keyword catches anything which isn’t True by the preceding conditions. It uses no conditional.
Example #5:
a = 555
b = 20
if b > a:
print(“b is greater than a”)
elif a == b: (this is described in the next section. Needs to be corrected)
print(“a and b are equal”)
else:
print(“a is greater than b”)
OUTPUT: a is greater than b
In this example, a is greater than b, so the first condition is not True, also the elif condition is not True, so we get to the else condition and print to the screen.
- You can also have an else without an elif:
Example #6:
a = 555
b = 20
if b > a:
print(“b is greater than a”)
else:
print(“b is not greater than a”)
OUTPUT: b is not greater than a
4.4 Elif (A4.6 - A4.7)
- The elif keyword is a shorthand way for Python to say “if the previous condition is not True, try this condition”. The term comes from a combination of the words Else-If.
Example #7:
x = 8
if x < 8:
print(“x is less than 8.”)
elif x == 8: # Notice the double equals, not single.
print(“x is equal to 8.”)
OUTPUT: x is equal to 8.
The first condition is False, so the program continues to the next condition and checks if x equals 8. It does and the print statement is executed. Notice that we use a double equals to check if two things are equivalent. The single equals in the first line of the program assigns whatever is on the right to whatever is on the left.
- It is possible to use multiple elif statements. Once a condition is True, the following ones are skipped. This is one entire logic block. You don’t need to keep checking once one of the conditions is True.
Example #8:
age = 78
if age < 12:
print("One CHILD ticket.")
elif age < 65:
print("One ADULT ticket.")
elif age < 150:
print("One SENIOR ticket.")
4.5 Shorthand
4.5.1 Shorthand If
- If you have only one statement to execute, you can put it on the same line as the if statement. Here is a piece of code as an example:
if a > b: print(“a is greater than b”)
4.5.2 Shorthand If...Else
- If there is only one statement to execute, one for the if and one for the else, it can all be placed in the same line:
print(“A”) if a > b else print(“B”)
4.6 Logical Operators (and / or) (A4.8)
4.6.1 and
- The and keyword is called a logical operator. It is used to combine conditional statements. For something to evaluate to True using and, both conditions have to be True. An example in real life would be: You have to do your homework AND do well on tests to get a good grade.
Example #9:
a = 50
b = 30
c = 100
if a > b and a > c:
print(“Both conditions are True”)
This tests if a is greater than b, AND if c is greater than a.
4.6.2 or
- The or keyword is another logical operator like and. It is also used (like and) to combine conditional statements. In this case, just one of the conditions have to be True for the overall result to be True. An example in the real world would be: You can pay for your meal in cash OR with a credit card. Either one would work.
Example #10:
a = 50
b = 30
c = 100
if a > b or a > c:
print(“At least one of the conditions is True”)
4.7 Nested if (A4.9 - A4.10)
- You can have if statements inside other if statements. When something is inside another thing in computer science, it’s called nesting. The statement executed as a result of an if statement could be another if statement. This lets us make another decision after getting the results of a previous decision.
Example #11:
x = 180
if x > 100:
print(“Above 100!”)
if x > 200:
print(“and also above 200!”)
else:
print(“but not above 200!”)
OUTPUT: Above 100!
but not above 200!
Important note: Notice the indentation. After the first if statement, everything else is indented. That means that everything following that first if statement is contained within it. The second if statement (if x > 200) has a colon at the end of it and has one line indented after it. That if goes along with the else, because they are on the same level of indentation.
4.8 The pass Statement
- if statements cannot be empty, but sometimes, like when you are in the middle of writing a program, it may have no content. To avoid getting an error, you can use the keyword pass.
if a > b:
pass
4.9 if Statements and Functions
- Now that you have some serious programming tools, your programs will have to have organization and style that will make them easier to edit and read. The following is an example of a program written two different ways. The program is fairly simple, but is used to make a point. Both programs do the same thing and have the same output but are written differently.
Example #12a:
time = 10
if time < 7:
print("Time to make dinner:")
print("Preheat the oven.")
print("Cut the veggies.")
print("Marinate the chicken.")
print("Mash the potatoes.")
print("Put the chicken in the oven.")
print("Eat when it’s ready!")
elif time < 11:
print("Time to get ready for bed:")
print("Brush your teeth.")
print("Get in your PJs.")
print("Get in bed.")
print("Read a book.")
print("Go to sleep!")
Example #12b:
def make_dinner():
print("Time to make dinner:")
print("Preheat the oven.")
print("Cut the veggies.")
print("Marinate the chicken.")
print("Mash the potatoes.")
print("Put the chicken in the oven.")
print("Eat when it’s ready!")
def bedtime():
print("Time to get ready for bed:")
print("Brush your teeth.")
print("Get in your PJs.")
print("Get in bed.")
print("Read a book.")
print("Go to sleep!")
time = 10
if time < 7:
make_dinner()
elif time < 11:
bedtime()
While both of these examples do the same thing, the second program is considered to be more efficient. In the second program, you don’t really have to read what each of the two functions do to understand how the program works. You can start where the time variable is defined and see that if it’s less than 7, make_dinner() will be called. If it’s less than 11, bedtime() is called. This allows us to focus on the different parts of the program more easily.
Chapter 4: Assignments
A4.1 How many languages?
Create a program that asks the user how many languages they speak. The program should respond with “Wow. That’s a lot!” only if the user speaks three or more languages.
op
SAMPLE RUN #1:
How many languages do you speak?
3
Wow. That’s a lot!
Thank you.
SAMPLE RUN #2:
How many languages do you speak?
1
Thank you.
A4.2 Road Trip Checklist
ASSIGNMENT:
Create a program that runs through a checklist of items before heading out on a road trip. This should include gas in the tank, miles since the last oil change, check air pressure in the tires, and if there is any washer fluid.
PROGRAM STRUCTURE:
# Use “if” statements for the next four questions:
# Ask the user “How many gallons of gas are in the tank?”
# If the answer is less than 10, say “BETTER FILL UP!”
#
# Ask the user “How many miles since the last oil change?”
# If the answer is more than 5000, say “CHANGE THE OIL!”
#
# Ask the user “Have you checked the air pressure in the tires?”
# If the answer is “No”, say “BETTER CHECK THE TIRES!”
#
# Ask the user “Do you have washer fluid?”
# If the answer is “No”, say “GET SOME WASHER FLUID!”
#
# Print: Have a good trip!
SAMPLE RUN #1:
How many gallons of gas are in the tank?
3
BETTER FILL UP!
How many miles since the last oil change?
2000
Have you checked the air pressure in the tires?
No
BETTER CHECK THE TIRES!
Do you have washer fluid?
Yes
HAVE A GOOD TRIP!
SAMPLE RUN #2:
How many gallons of gas are in the tank?
13
How many miles since the last oil change?
14,000
CHANGE THE OIL!
Have you checked the air pressure in the tires?
No
BETTER CHECK THE TIRES!
Do you have washer fluid?
No
GET SOME WASHER FLUID!
HAVE A GOOD TRIP!
A4.3 Hi / Low
This program should ask the user for a number. It will then tell the user if the number is greater than or less than 100. The “Thank you” at the end should not be in the if-else block. (Try to understand why this program doesn’t work for input that is exactly 100. Why? This will be taken care of in a later assignment.)
PROGRAM STRUCTURE:
# This program is similar to 4.1 but will have an “if - else”:
# Use an “if - else” to determine if the input is above or below 100:
# if (conditional to check for less than 100)
# print: That number is lower than 100.
# else
# print: That number is greater than 100.
#
# print: Thank you.
SAMPLE RUN #1:
Please enter a number: 45
That number is lower than 100.
Thank you.
SAMPLE RUN #2:
Please enter a number: 1500
That number is greater than 100.
Thank you.
A4.4 Password with one chance
The user has one chance to get the password or they are not allowed in. In the program, you will set the password as: 5656.
PROGRAM STRUCTURE:
# This program is similar to 4.3 using an if-else statement
SAMPLE RUN #1:
Please give me the password. It is a four digit number. You have one chance!
5656
You may enter….
SAMPLE RUN #2:
Please give me the password. It is a four digit number. You have one chance!
2345
You may NOT enter….
A4.5 Modulus Quiz
This program will pose two questions to the user to test them on their knowledge of modulus calculations. You will make up these questions yourself and other students will test themselves with your program. A True or False question will be posed. That answer will be evaluated.
PROGRAM STRUCTURE:
# First question:
# If (check for correct answer being TRUE)
# That is correct!
# else
# That is wrong!
# Second question:
# If (check for correct answer being TRUE)
# That is correct!
# else
# That is wrong!
SAMPLE RUN:
I will ask you a question, and you will tell me if it’s TRUE or FALSE:
The value of 14%10 is 4? (TRUE or FALSE)
true
That is correct!
Here is your second questions. Tell me if it’s TRUE or FALSE:
The value of 5%6 is 0? (TRUE or FALSE)
true
That is wrong!
A4.6 Hi Low Equals
This is similar to 4.3 (Hi/Low) but you need to use an else-if because three cases are being evaluated. This program should ask the user for a number. It will then tell the user if the number is greater than 100, equal to 100, or less than 100.
SAMPLE RUN #1:
Please enter a number:
89
That number is lower than 100.
Thank you.
SAMPLE RUN #2:
Please enter a number:
110
That number is greater than 100.
Thank you.
SAMPLE RUN #3:
Please enter a number:
100
100! That number is the same as ten to the power of two!
Thank you.
A4.7 Flipper rental fitting
Write a program that recommends the appropriate flipper size that should be rented based on your shoe size. The following recommendations should be made:
0 - 5 - small
6 - 9 - medium
10 -14 - large
14 and above - No flippers available
SAMPLE RUN #1:
What size is your shoe?
5
You need small flippers.
SAMPLE RUN #2:
What size is your shoe?
11
You need large flippers.
SAMPLE RUN #3:
What size is your shoe?
16
We have no flippers for you.
A4.8 Check a Range
Create a program that asks the user for a number between 50 and 100, not including those numbers. Use only one if statement and one else.
SAMPLE RUN #1:
Please enter a number between 50 and 100:
32
That number is not appropriate.
SAMPLE RUN #2:
Please enter a number between 50 and 100:
77
Thank you!.
A4.9 Driving Questionnaire
Create a series of questions that involve nested ifs. Use the sample runs below for details.
PROGRAM STRUCTURE:
# if (check for 16 or older is TRUE):
# print: Do you have a driver’s license?
# if (check for driver’s license is FALSE):
# Print: I guess I will drive!
# else:
# Print: You drive!
# else:
# print: Get in the back seat
SAMPLE RUN #1:
Are you 16 or older? (1 = Yes, 2 = No)
Yes
Do you have your driver’s license? (1 = Yes, 2 = No)
No
I guess I will drive!
SAMPLE RUN #2:
Are you 16 or older? (1 = Yes, 2 = No)
No
Get in the back seat!
A4.10 Buying a Ticket
This program will determine the price of a ticket based on the age. There are Child, Adult and Senior ticket prices.
PROGRAM STRUCTURE:
# if (check if between 18 and 65 years old is TRUE)
# print: You will be charged an adult fare
# else
# print: Are you a child or senior?
#
# if (check for child is TRUE)
# Print: You will be charged a child fare
# else
# Print: You will be charged a senior fare
SAMPLE RUN #1:
Are you between 18 and 65 years old? (1 = Yes, 2 = No)
1
You will be charged an adult fare.
SAMPLE RUN #2:
Are you between 18 and 65 years old? (1 = Yes, 2 = No)
2
Are you a (1) child or (2) senior?
1
You will be charged a child fare
CH. 4 PROJECT: Choose your own adventure
This project will require you to create your own “choose your own adventure” story. The structure of the program will be based on nested ifs. The player gets to choose between two options at each stage of the story. There should be eight paths through the story as described in the tree structure below.
IMPORTANT: Take time to plan this out! Use functions for each part of the story. The main flow of the program should not include any of the actual story content but should only have the simple structure of the story. Each time a choice is made by the user, a function should be called to print the next section to the screen. Once the section is printed, control should go back to the main part of the program.
STRUCTURE:
The opening of the story should have two options (1 and 2)
Options 1 and 2 should each have 2 options (1a, 1b and 2a, 2b)
Each of those options should have 2 options (1aa, 1ab and 1ba, 1bb and 2aa, 2ab and
2ba, 2bb)
You can make the story longer if you wish, but it must have this structure at least.
Opening
/ \
1 2
/ \ / \
1a 1b 2a 2b
/ \ / \ / \ / \
1aa 1ab 1ba 1bb 2aa 2ab 2ba 2bb
SAMPLE RUN: (just the beginning)
You wake up to find yourself in a room. The door is locked. What do you do?
- Bang on the door for help
- Investigate what is in the room
If the user chooses 1:
Someone comes to the other side of the door and says: “I can’t open the door. I
have to call the fire department. Can you try to climb out the ceiling?”
- Answer yes and try to climb out the ceiling.
- Answer no and wait for the fire department
If the user chooses 2:
You look around the room and find an envelope. You open it and in it is a picture
of a man holding a sign that says: “If you are reading this, you are in trouble.
Follow my directions carefully. First thing, no matter what, don’t open the cabinet.” You look around and see a cabinet. Do you open it?
- Yes
- No