Python Control Flow (If…Else)

Usually, you need to make some decisions in the flow of your program. These decisions are made using flow control statements that determine the statements to execute. In Python If, Elif, Else statements are used to control the flow of a program.

Comparison Operators

Comparison Operators are used together with If statements to make decisions. The following table shows comparison operators.

OperatorDescription
==Equals
!=Not Equals
<Less Than
<=Less Than or Equals
>Greater Than
>=Greater Than or Equals

If Statement

If statement is the most commonly used control statement. Code block under if statement is executed, when the condition evaluates to true.

While most programming languages use braces {} to specify if blocks, Python uses indentation. All the code that will be executed is indented with the same level of indentation (4 spaces per indentation level is preferred).

x = 100
if x == 100:
    print("x is equal to 100.")

Elif Statement

Elif (Else If) statement follows an if-statement or another elif statement. Elif statement means, check this condition if all if/elif statements above are evaluated to false.

The sample code below checks the score. If it’s 100, then it will not evaluate other elif/else statements below. If the score is not 100, flow continues with the next elif (or else) statement.

score = 90
if score == 100:
    print("Congratulations, you have a perfect score!")
elif score>70:
    print("Well done, you have passed.")

Else Statement

Else statement is used under all if/elif statements. If none of the if/elif statements are evaluated to true, the else code block is executed.

score = 100
if score == 100:
    print("Congratulations, you have a perfect score!")
elif score > 90:
    print("Congratulations, you scored very well.")
elif score>70:
    print("Well done, you have passed.")
else:
    print("You have failed, you need to practice more.")
SHARE