Python If-Else Condition

Posted on July 22, 2020 by Mr Writer

In this tutorial, You’ll learn about Python Conditional Statements such as IF, IF-ELSE, IF-ELIF, Nested IF, and Switch Statements.

The Conditional Statements take up the responsibility for logic flow across the programing and these take such decisions based on conditions specified by the programmer.

The logical operators such as OR, AND, EqualTo are used to arrive at a discussion on whether to continue program flow or not.

Table of Contents

How to write if a statement in Python?

Use keyword if followed by expression and end that expression using colon ( : ) symbol. And in between their goes the logical comparison as shown below where variable a is compared to variable b to check which is greater ( > ).

a = 10
b = 9

if a > b:
    print("Yes the variable a is greater than b")

# PYTHON OUTPUT
Yes the variable a is greater than b

Logical Operators with Symbols and meaning.

  • >: This is greater than the operator.
  • <: This is lesser than the operator.
  • ==: This is equal to the operator.
  • !: This is not an operator and is used with equal to the operator such as 6 != 5 .

How handle else condition?

The If Condition executes only when the expression return True else the program logic is not allowed to access statements inside If condition. But there is a provision to handle execution flow i.e using else statement.

a = 3
b = 4

if a > b:
    print("Yes the variable a is greater than b")
else:
    print("No the variable a is lesser than b")

# PYTHON OUTPUT
No the variable a is lesser than b

Here the logical expression a > b returns False and the data inside else statement is executed.

How to write Ladder If Condition using ELIF Statement?

You can also chain multiple If Conditions one below another and this is called ladder if Condition.

Note

while using Ladder If Statements, Instead of using else use elif statement followed by the expression.

a = 7
b = 10
c = 9

if a > b:
    print("Yes the variable a is greater than b")
elif b > c :
    print("Yes the variable b is greater than a and c")
else:
    print("Yes the variable c is greater than b and a")

# PYTHON OUTPUT
Yes the variable b is greater than a and c

Write Nested If Condition

If Conditions written inside one another is called Nested If Conditions. They are mostly used for nested level conditional checking where you need to check many conditions one after the other.

if <condition>:

    if <condition>:

        if <condition>:
            # statement
else:

    if <condition>:
        # statement

#python #learn python #if-else

Python If-Else Condition - The Code Learners
1.20 GEEK