As you would have learnt in the Pseudocode Tutorial, conditionals are used when we want to check whether a statement is True or False
The syntax of conditionals is as follows:
if '''insert condition here''':
#code to run if True
else:
#code to run if False
Notice that after the colon, we left spacing before we add the code. This is known as indentation, and it is used to specify the code which is contained inside the conditional i.e. the code will only run if the condition is satisfied. Let us now look at a real example of how it works.
#Q: Write a program to check whether a user is eligible to drive. You must be 18 or older to be able to drive.
age = int(input("Enter your age here: "))
if age >= 18:
print("You are allowed to drive") #if a person is 18 or older, this text wil be displayed
else:
print("You are not allowed to drive") #if a person is less than 18, this text will be displayed
As you can see, I entered my age as 19 which resulted in me being allowed to drive. If I had entered my age as 16 I would not be allowed to drive.
"""Q: Write a program to calculate the letter grade a student will receive based on their percentage.
A is greater than 80%, B is greater than 60% and C is greater than 40%. Anything else is fail. """
percentage = float(input("Enter your percentage here: "))
if percentage>80:
print("A")
elif percentage>60 and percentage<=80:
print("B")
elif percentage>40 and percentage<=60:
print("C")
else:
print("Please attempt again.")
Now let me write the same program in a different way to show how elif really works.
percentage = float(input("Enter your percentage here: "))
if percentage>80:
print("A")
else:
if percentage>60 and percentage<=80:
print("B")
else:
if percentage>40 and percentage<=60:
print("C")
else:
print("Please attempt again")
As you can see, we got the same result. Using ELIF instead of nested IFs looks more elegant and makes writing a program much easier, which is exactly what Python is all about.
In Python, be sure to keep in mind the indentation levels you are using as the Python Interpreter checks indentation levels and produces an error if theres an error, let's look at an example.
number = 2
if number < 3:
print("2<3")
else:
print("2>3")
That brings us to the end of this tutorial. Go Check out our other Python Tutorials to learn more!