Beginner: If Statements
Welcome to the Week 2 Beginner Python Notebook. This notebook is designed for students who are just starting out with the Python programming language.
Your task today is to read through the material carefully and complete the exercises provided at the end. These exercises are an important part of the learning process and will help you check your understanding.
Important: You have three options for today’s work:
Beginner,Intermediate, orAdvanced. If you are new to Python, please choose this Beginner notebook. You will have plenty of opportunities later in the course to explore the other levels.
In this notebook, you will be introduced to the if statement; a powerful feature of Python that lets you control when certain pieces of code are executed.
Be sure to work through the examples and attempt all the exercises. They are designed to reinforce your learning and build your confidence.
Table of Contents
Recap: Booleans
Last week, we met Boolean variables. These were variables which can take the values True or False.
We often create booleans by comparing other variables to one another:
We can save the value of a boolean comparison like so:
Python has several operators to combine or modify booleans:
To summarize: - Booleans are always either True or False. - Comparisons (>, <, ==, !=, in) produce Boolean values. - Boolean operators (not, and, or) let us combine or flip conditions.
Today, we shall look at using Booleans to perform conditional operations. That is, we shall write code which executes only when certain circumstances hold. To do so, we shall introduce the if statement.
The if Statement
An if statement allows you to run a block of code if and only if a boolean expression is True. Take the example in the following block, for instance. In this example, “Positive” is printed if the variable my_number is greater than \(100\).
Test your understanding: Try changing the value of
my_numberin the above code to be negative. Before moving on, think about what might be happening here; How do you think theifstatement decides which statements to print?
Let’s break down exactly what is going on in this if statement.
An if always follows the same layout. First, it must include the if keyword and a colon :, like so:
↓ ↓
if my_number > 100:
print(my_number, "is large")
In between the if and the :, we must place a boolean variable. The idea here is that we want our code to execute (run) if and only if this boolean is true. In our example the boolean is my_number > 100.
↓
if my_number > 100:
print(my_number, "is large")
We next need to add a body. The body is the lines of code that will be run if the condition has been met:
if my_number > 100:
print(my_number, "is large") ← body of the if statement
Python will only recognise code as being in the body of the if statement if it is indented. This means that all code in the body must be indented relative to the word if by four spaces. A trick to help remember this is that every time you see a colon in Python you should start a new line and indent:
colon
↓
if my_number > 100:
print(my_number, "is large")
↑
indentation
Code that is not indented will be treated as being outside the if statement and run in the usual manner.
if my_number > 100:
print(my_number, "is large")
print("This is always printed") ← this code will always run as it is outside the if statement
Here are some more examples of if statements.
Note that, in the above examples, we have always defined our boolean variable directly between the if and colon :. We didn’t have to do this; we could have instead defined the variable first like so:
In practice, it’s often simpler not to define a separate boolean variable explicitly like we did above. Deciding whether to store something like x_is_positive depends partly on whether you’ll need to reuse it later and partly on personal preference.
else
We’ve just seen that the body of an if statement will only run if the boolean is True. But what if we want to do one thing if it’s true, but another if it’s false? We can do this by attaching an else statement to the if statement, like so:
Warning: The
elsestatement must be at the same level of indentation as theifkeyword. If not the code will throw an error, like so:
elif
Sometimes an if-else statement isn’t enough, because you want to check more than two possibilities. For such situations, we can use the elif keyword.
elif stands for ‘’else if’’. It lets you add extra conditions to your decision-making. For instance:
There are a few rules to keep in mind here:
- The order matters: we start with
if, then add as manyelifstatements as you need, and finish with an optionalelse. - You can only have one
ifand oneelse, but you can include any number ofelifstatements in between. - If one of the statements evaluates as
True, the remaining code will not be executed, regardless of the truth of the remaining conditions.
Here are some more examples of this concept in action.
Warning: Indentation is crucial for
ifstatements in python. You must indent blocks of code within if statements as this is how the blocks of code are delineated in python.
Warning: Make sure to remember the colon on the end of the
if,elifandelsestatements! Without this Python, will throw an error. This error often causes many a headache for new Python users!
Worked Example: Determining a Leap Year
Say we wanted to determine whether a year is a leap year (a year with 366 days rather than the usual 365).
The first thing we know is that a leap year generally happens every 4 years. So to start off we could impose the following condition:
Recall: Last week, we saw that the
%operator represents modular arithmetic. This means thata % bgives the remainder whenais divided byb. For example,10 % 3gives1. The above code works as ifyear % 4equals0, then theyearmust be divisible by4.
The rules for determining leap years in the Gregorian calendar are a bit more nuanced than simply being divisible by \(4\). In fact, if the year is also divisible by \(100\), then it is not a leap year (e.g., \(1800\), \(1900\), \(2100\)).
We need to add this new condition to our if statement. This can be done by combining year % 4 == 0 and year % 100 == 0 using an and clause:
Let’s try adding a new block to account for the situation where even if the year is divisible by \(4\), if it is also divisible by \(100\) it is not a leap year.
But this isn’t right - we saw above that \(1900\) is not a leap year so this should say
Is 1900 a leap year? No
Let’s go through this line by line. Python checks the first criteria in the if block year % 4 == 0:
As this boolean is true, the if statement stops when it is evaluated and exits without checking the other clauses.
So how do we make sure Python checks the correct set of conditions first? To do this we have to think about the ordering of the clauses:
Now Python checks the more strict clause first and then exits when the condition year % 100 == 0 and year % 4 == 0 is true:
This updated if statement now gives us the behaviour we desired.
Exercises
Question 1: Create a string containing your last (or first) name. Write an if statement to check if the length of this string is greater than 8. If true, print “The name is long”.
Hint: Recall the len() function can be used to check the length of strings.
Question 2: The pH value of a liquid can be used to determine whether it is acidic, alkaline, or neutral. Write some code which uses the variable ph_level to assign the correct liquid_type ("acid", "alkali", or "neutral").
Now, modify your code to set liquid_type="unknown" if ph_level does not lie on the pH scale.
Question 3: The following code is intended to classify the state of water based on its temperature in °C:
However, when you run the code with temperature = 120, the output is:
State of water: liquid
But at 120 °C, water should be a gas, not a liquid! Explain why this program gives the wrong result and modify the code to give the correct result.
Question 4: In the code box below, the variable day_number represents the day of the year. For example, if day_number = 8, the date is January 8th, and if day_number = 32, the date is February 1st. Write an if statement that determines the current month based on the value of day_number. You may assume the year is not a leap year and that day_number is an integer strictly greater than 0 and strictly less than 366.
Question 5: Now suppose you want to adapt your code from Question 4 so that day_number can fall outside the usual range of 1 to 365. For example, day_number = 366 should “wrap around” to January 1st, while day_number = 0 should correspond to December 31st. How would you modify your if statement to handle this? Write your code below. For simplicity, you may continue to ignore leap years.
Hint: The % operator might be useful here!
Question 6: The code below has a distance given in kilometres. Assuming 1 mile ≈ 1.60934 km, convert the distance in km to a distance given in miles. Write code which does the following:
- If the distance is greater than 2 miles, print “Distance is more than 2 miles”.
- Print “Distance is short” if this condition is not met.
- Add an additional check if
distance_in_milesis > 1 mile and print “Distance is more than 1 mile” if true.
Question 7: The leap year example given in the worked example section is incomplete. The full definition of a leap year is as follows;
- A year is a leap year if it is divisible by \(4\) but not by \(100\).
Unless…
- If the year is divisible by \(400\), then it is a leap year after all (e.g., \(2000\), \(2400\)).
Modify the example of the worked example section to incorporate this final bullet point.
Question 8: By performing your own research online, explain what the keyword pass does in the code below and why you might use it.
What do you think would happen if you removed the line with pass from the code above?
Question 9: FizzBuzz is a children’s counting game played with the following rules:
- Players take turns counting up from
1. - If a number is divisible by
3, say"Fizz". - If a number is divisible by
5, say"Buzz". - If a number is divisible by both
3and5, say"FizzBuzz". - Otherwise, say the number itself (as a string).
It’s now your turn. You are given the previous player’s answer, prev_answer, along with the number they just counted, prev_num. Using an if–elif–else statement, print the correct response for your turn.
Modify your code so that if the previous player’s answer was incorrect, your program prints a message pointing out the mistake before giving your own response.
Question 10: The code below contains a horrendous nested if statement. By combining cases using the and and or operators, reduce the long nested if statement to a single if–elif statement.