Milandeep Bassi

Using Selection in the form of if, else and elif in Python Programming

27th, January, 2020


If Statements

The structure of an if statement is very simple. The expression is first evaluated with a Boolean value (True or False). If the statement is true, the code will be executed otherwise it is skipped. With if statements it's wise to use the Comparison operators we learned when discovering how to use While loops.

if <expression>:
statement
statement
...

Selection statements such as this can be nested inside each other, to perform multiple checks essentially. This can also happen with repetition statements such as while.


Else Statements

An else statement is combined with an if statement to execute some code when the if expression is equal to false. There can only be one else statement following on from the if statement. 

if <expression>:statement
statement
else:
statement


Elif Statements

The elif statement allows you to check multiple expressions for a True result. Once an elif statement is selected it will execute that block of code and continue without checking anymore. It's more efficient than using multiple if statements. Unlike an else statement there can be any number of these. 

if <expression>:
statement
elif <expression>:
statement
elif <expression>:
statement
else:
statement

A break statement can be used inside the if statement or inside a while loop to exit the loop or statement early. 


Writing Your First Selective Programme

We're going to create an application to tell you if the days in a month, for a non-leap year. So to start you will need to open up IDLE and create a new file script. 

Selective Programme

You will then need to first assign the users input for the month. You can do this by using str(input("...")). After this what we've done is use the month.lower() command to make sure all inputs into the program are consistent. Now that we're done with assigning the inputs we move onto evaluating these. So the next line will be if month == "january": . The reason that January is lowercase since we converted our input to this for safety reasons. Following up this you should print your desired message for the user.

Now you need to define the rest of the months in the year. You can do this using an elif as if the code is selected then the program completes.

Selective 2

Finally you can add an else statement incase a user does not enter the month prompting the program to report an error to the user and exit. 

Selective 3

To make the program more complicated you could add a While loop over the code to make it so the program will not exit after calculating one of the months or after an incorrect input. Try this out and experiment with the selections!