Beginning Python

Conditionals

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:

if.py
my_number = 128

if my_number > 100:
    print(my_number, "is large")
$
python if.py
128 is large

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:

if.py
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
Enter a number: 128
128 is large

Exercise 1

Run the program with different inputs. Does it give you what you expect? What happens if the input is smaller than 100?

answer

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

Booleans

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.

Exercise 2

Experiment with editing if.py to use some different boolean statements. Make sure you remember to save the file after each change before running it.

answer

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:

if.py
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:

if.py
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.

Ordering your options

When working out which lines of code will be run, Python will work down the list of if, elifs 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:

if.py
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")

Combining questions

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.

Exercise 3

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:

  1. if the year is divisible by $400$ then it's a leap year,
  2. otherwise, if the year is divisible by $100$ then it's not,
  3. otherwise, if the year is divisible by $4$ then it's a leap year,
  4. otherwise, it's not.

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:

  • $2023$ - not a leap year as it's not divisible by $4$
  • $2024$ - a leap year as it's divisible by $4$ (and not by $100$)
  • $1900$ - not a leap year as it's divisible by $100$ (and not by $400$)
  • $2000$ - a leap year as it's divisible by $400$

answer