Conditionals are programming constructs used to make decisions based on whether a particular condition is true or false. Conditionals are used to execute different blocks of code based on different circumstances. Python provides several types of conditional statements that allow for different execution of commands.
The most basic version of a conditional is a simple if-statement. If the condition is true, a specific block of code will be executed. For example:
age = input("How old are you?")
if age >= 18:
print("You are old enough to vote")
In the above example, the user is prompted for their age which gets stored in the age variable. If the age is greater than or equal to 18, the program prints out the message “You are old enough to vote”.
To add additional selection of conditions, we can also add an else statement following the if statement which will get executed if the condition being checked is false. For example:
age = input("How old are you?")
if age >= 18:
print("You are old enough to vote")
else:
print("You are too young to vote")
The example above will now check the same condition as the previous example, but this time if the age entered is not greater than or equal to 18, it will print out an alternate message: “You are too young to vote”.
To add even further selection of conditions, we can create an elif statement in between the if and else blocks that can check an additional condition if the first one is false. For example:
hour = input("What hour of the day is it?")
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")
The above example creates three possible outputs, according to the value of the hour variable. Notice that the elif condition is only checked if the first condition hour < 12 is false.
We can add in as many elif statements as we like to provide for multiple possible paths in the code. For example:
score = input("Enter your percentage score")
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(grade)
As we can see in the example above, the ordering of our conditions is important. We always want to put the most specific case first, and gradually work our way down with each condition. This allows us to write the most efficient code and ensure we are achieving the desired output.
Python is all about indentation when it comes to formatting and differentiating between various blocks of code.
A code block (conditionals, functions, loops, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. You may receive an error message or an unexpected output if your code is not properly indented as you desire. When dealing with conditionals, it is important to use indentation to indicate the start and end of a given block.