We've seen loops are one way of changing the default "top to bottom" reading of Python scripts. Loops are an example of control flow statements. Another very useful tool in Python is the conditional. This, rather than allowing you to repeat parts of the program, gives you the ability to skip parts depending on certain conditions.
The simplest place to start is the if
statement. This lets you only run a block of code if a certain condition is true. Copy the following code into a file called if.py
and run it with python if.py
in the terminal:
my_number = 128
if my_number > 100:
print(my_number, "is large")
python if.py
To explore the behaviour of the if
statement, we could edit the if.py
script to change the value of my_number
, but instead let's change it to that it's set via an input
function call. The input
function will always return a string, even if you enter digits so we need to explicitly convert the input into an integer with the int
function:
my_number = int(input("Enter a number: ")) # We can nest function calls directly
if my_number > 100:
print(my_number, "is large")
python if.py
if
statement syntax¶An if
statement has a similar sort of structure to a for
loop in that it has scaffolding as well as user-supplied parts. The scafolding is the word if
and the colon again:
↓ ↓ if my_number > 100: print(my_number, "is large")
and the user-supplied part is the conditional:
↓ if my_number > 100: print(my_number, "is large")
As before, the body must be indented by four spaces:
colon ↓ if my_number > 100: print(my_number, "is large") ↑ indentation
If we take a closer look at that user-supplied conditional we'll see it's made up of three parts, some data on either side of a greater-than sign (>
). In Python this means "is my_number
more than 100
?". It's asking a question and in Python the answer to a question like this can be either True
or False
.
For example,
128 > 100
is True
, and:
56 > 100
is False
.
The results of these questions are booleans. True
and False
are values in the same way that 12
and "Hello"
are values but belong to their own data type.
Other boolean operations we can perform are:
334 < 98 # Less than
76 == 70 + 6 # Are they equal to each other?
3.14159 != 3 # Are they *not* equal to each other
4 <= 43 # Less than or equal to
45 >= 17 # Greater than or equal to
Notice that when comparing two values, we use a double equals sign (==
), wheras we used a single equals sign (=
) to create a variable.
We also used a #
symbol in this code to denote a "comment". Comments are ignored by Python when running your code which means you can use them to explain to other humans reading your code what it's doing. This is a good idea if there's anything non-obvious in your code.
else
¶We've just seen that the body of an if
statement will only run if the conditional 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:
my_number = int(input("Enter a number: "))
if my_number > 100:
print(my_number, "is large")
else:
print(my_number, "is not large")
The else
statement must be at the same level of indentation as the if
keyword and does not have any option for the user to provide a boolean statement to it. In this case, you can guarantee that one and only one of the two bodies will run.
elif
¶If you do want to provide a boolean statement to an else
then you can use an elif
instead. It stands for "else, if ..." and it allows you to refine the questions you are asking:
my_number = int(input("Enter a number: "))
if my_number > 100:
print(my_number, "is large")
elif my_number < 0:
print(my_number, "is negative")
else:
print(my_number, "is not large")
You can again rely on at most one of the branches being run.
When working out which lines of code will be run, Python will work down the list of if
, elif
s and else
and will run the first one that matches. Once it's matched one, it will not bother checking to see if any of those later on would have matched. This means that you should order your questions from most-specific to least-specific.
For example, if you want to do one thing for positive numbers, but something special instead for numbers greater than 100, then you should put the more specific check first:
my_number = int(input("Enter a number: "))
if my_number > 100:
print(my_number, "is large")
elif my_number > 1:
print(my_number, "is positive")
else:
print(my_number, "negative")
It is possible to ask two or more questions in one go by combining them with and
and or
. So, if you want to check is a number is smaller than ten (my_number < 10
) and is not equal to zero (my_number != 0
), you can use:
if my_number < 10 and my_number != 0:
...
These combined checks can be used is both if
and elif
statements.
Create a file leap_year.py
which calculates, for a given year, whether it is a leap year and prints out the answer. You might want to read the year in using input
, or you could hard-code it in the program.
The rules to follow are:
To simplify the writing of the program, you might find it easier to start with the divisible-by-$4$ condition, then add in the divisible-by-$100$ check and then add in the divisible-by-$400$ calculation.
For reference, here are some years for you to check against: