Python if else statement
It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example of previous tutorial, we will want output whether the grade is passing or failing.
Python If Else Syntax :
if condition:
statement
else:
statement
To do this, we will add an else statement to the grade condition above that is constructed like this:
grade = 60
if grade >= 65:
print("Passing grade")
else:
print("Failing grade")
Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.
When we save and run the program, we’ll receive the following output:
Failing grade
If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.
advertisement