Conditional Statements
Introduction to conditional statements in Python, including "if" statements.
Conditional statements are one of the first logical flows you will learn. They're fundamental in almost every programming language, and allow you to execute different blocks of code based on different conditions being satisfied. Hence they're called "conditional statements".
The syntax of a conditional statement in Python is as follows:
Changes in indentation (like on line 2) signify the start and end of the block of code to be executed.
Changes in indentation (like on line 2) signify the start and end of the block of code to be executed.
This program takes an integer from the user, and outputs "Good morning!" or "Good afternoon!" based on the integer value. It makes use of the int()
function to force the conversion of the user's input into the integer data type, so that it can be processed as such.
But, what if both conditions are met in the above program, such as with an input of 12? Well, both blocks will be executed! How do we ensure only the first satisfied block is executed? Using the elif
statement:
Here, not only have we ensured only one block will ever be executed, but we've made use of several elif
statements to also include an output for "Good evening!".
There is no limit as to how many consecutive if
or elif
statements you can use.
This is great, but what if we want to inform the user they're entering wrong data if they input a value outside of the range 0-23. We could adjust the conditions, but why not use the added else
statement?
Now the program will output "Please enter an integer in range 0-23!" if the user attempts to enter any integer outside of this range. Awesome!
You should only use one else
statement at the end of a sequence of if
and elif
statements.
If the user inputs a value that can't be converted into an integer, an error will be thrown by the program!
Last updated