If, Else If, Else

The if/else statement executes different blocks of code based on whether a condition is True or False. The following if/else statement checks if a student’s grade is greater than 60:

grade = 85
if grade >= 60:
	print('Passed')
else:
	print('Failed')

The condition of the if statement above is True, so the program displays ‘Passed’. Note that when you press. If the variable grade were assigned to 50 instead, the condition of the if statement would be False, which means the program would display Failed instead. Ultimately, if your if statement’s condition is True, then the body of the else statement is not executed. If the condition of the if statement is False, then the body of the if statement is skipped and the body of the else statement is executed. You can add any valid statement that you would like to the body of an if or else statement. You can also add as many statements as you would like!

You can test for many cases using the if/elif/else statement. The following program displays “A” for grades greater than or equal to 90, “B” for grades in the range 80– 89, “C” for grades 70–79, “D” for grades 60–69 and “F” for all other grades:

grade = 75

if grade >= 90:
	print('A')
elif grade >= 80:
	print('B')
elif grade >= 70:
	print('C')
else:
	print('F')

The first condition — grade >= 90 — is False, so print(‘A’) is skipped. The second condition — grade >= 80 — also is False, so print(‘B’) is skipped. The third condition — grade >= 70 — is True, so print(‘C’) executes. Then all the remaining code in the if/elif/else statement is skipped. An if…elif…else is faster than separate if statements, because condition testing stops as soon as a condition is True.

The else in the if/elif/else statement is optional. Including it enables you to handle values that do not satisfy any of the conditions. When an if/elif statement without an else tests a value that does not make any of its conditions True, the program does not execute any of the statement’s found in the bodies. The next statement in sequence after the if/elif statement executes. If you specify the else, you must place it after the last elif; otherwise, a SyntaxError occurs.