3 months ago

Branching: Learn If, Else and Elif in Python

Give your Python programs smarts with conditional branching: If, Else and Elif

Branching is  an all important concept to learn when programming in Python. If, Else and Elif statements enable your program to be smart and make decisions.

We’ve looked at a lot of Python programs lately, and our programs have been slowly getting more powerful. We’ve learned to run instructions in procedural order, replaced parts of our program with variables, and looped over the code.

This article is based on Beginner’s Guide to Coding in issue 53 of The MagPi. Issue 54 of The MagPi has a companion piece on learning object orientated programming with a Raspberry Pi

See also:

One important part of programming is called ‘conditional branching’. Branching is where a program decides whether to do something or not.

Branching with If in Python: learn the logic

A program doesn’t just decide whether or not to do things on a whim: we use the sturdy world of logic here.

The start of all this is the powerful ‘if’ statement. It looks similar to a loop, but a condition runs just once. The if statement asks if a condition is True. If it is, then it runs the indented code (remember we indent our code with four spaces; not a tab):

Run this program, and it’ll display ‘Hello World’. Now change the if statement to False:

…and nothing will happen.

Of course, you can’t just write True and False. Instead, you create a condition which evaluates to True or False; a common one is the equals sign (==). This checks whether both items on either side are the same. Create a new file and enter the code from password1.py.

Password.py

This code is a simple program that asks you to enter a password; if you enter the correct password, ‘qwerty’, it displays ‘Welcome’.

Be careful not to confuse the equals logic operator == with the single equals sign =. While the double equals sign checks that both sides are the same, the single equals sign makes both sides the same. Getting == and = mixed up is a common mistake for rookie coders.

Branching: using If Else in Python

After if, the next conditional branch control you need to learn is ‘else’. This command is a companion to if and runs as an alternative version. When the if branch is True, it runs; when the if branch is False, the else branch runs.

Run this program and you’ll see ‘The first branch ran’. But change True to False:

…and you’ll see ‘The second branch ran’. Let’s use this to expand our password program. Enter the code from password2.py.

Password2.py

Run the program again. If you get the password correct now, you’ll get a welcome message. Otherwise, you’ll get an ‘incorrect password’ message.

Branching: use If, Else, and Elif for smarter coding

The third branching statement you need to know is ‘elif’. This statement stands for ‘else if’, and sits between the if and else statements. Let’s look at an elif statement. Enter this code:

Run this program and you’ll find it skips the first if statement, but runs the elif statement. You’ll get ‘The second block of code ran’.

The else statement doesn’t have a True or False condition; it runs so long as neither the if or elif statements are True. (Note that the else statement here, as always, is optional; you can just have if and elif.)

But what happens if you change both the if and elif conditions to True? Give it a try and see whether just if runs, or elif, or both. Experiment with removing the else statement and play around. It’ll help you get the hang of the if, elif, and else statements.

Branching at work: create FizzBuzz in Python

We’re going to show you a common program used in computer programming interviews. It’s a classic called ‘FizzBuzz’, and it shows that you understand if, else, and elif statements.

First, you need to know about the modulo operator (%). This is used to get the remainder from a division and is similar to a divide operator. Take this function:

If we use a modulo instead, we get this:

Modulo turns out to be handy in lots of ways. You can use % 2 to figure out if a number is odd or even:

This program works out if a number is odd or even:

OK – let’s move on to FizzBuzz.

Code your own FizzBuzz program in Python

The brief for our FizzBuzz is to print the numbers from 1 to 100. If a number is divisible by three (such as 3, 6, and 9), then you print ‘Fizz’ instead of the number; if the number is divisible by five, you print ‘Buzz’ instead.

But if a number is divisible by both 3 and 5, such as the number 15, then you print ‘FizzBuzz’.

We’re introducing you to a new element in FizzBuzz: the ‘and’ statement. This checks if two conditions are both True: that the number can be divided by both 3 and 5. It only returns True if both conditions are True.

There are three main logical operators: and, or, and not. The first two are relatively straightforward, but the ‘not’ operator can be more confusing at first. Don’t worry about it too much; you’ll get the hang of it with practice.

Enter the fizzbuzz.py code to practise using if, else, and elif elements and logical operators.

fizzbuzz.py

Logical operators in Python

You can combine conditions together using logical operators. Here are three logical operators available to you:

  • and Both operands are true: (a and b) is True
  • or Any operator is true: (a or b) is True
  • not Checks if something is false: not (a and b) is True if both a and b are False.

Learn to comment your code in Python

A mark of a good programmer is to use comments in your programs. Comments are used to explain bits of your program to humans. They are completely ignored by the computer.

In Python, you start a comment line with a hash symbol (#). It can be on a line on it own, or it can come right after a line of code. As soon as Python hits the #, it’ll stop translating whatever follows into machine code.

Comments help other users to read your program, but they will also help you understand what you’re doing (long after you’ve forgotten). It’s a good habit to use comments in your programs.

  • John Dux

    The ‘count += 1’ statement needs to be indented to work as expected