top of page

Python If-Else conditional Statement

It uses to check the condition. If return true value and else return a false value.

We can easily learn it by using some examples, as per given below:

IF...ELSE is used to control the flow of program. it's also known as control statement. Flow control statements is used when we can execute block of code when certain conditions is satisfied.

Example if statement

An "if statement" is written by using the if keyword.

a = 10

b = 5

If a>b:

     print(“The largest number is”, a)

In the above example, a and b are two integer variables where a is equals to 10 and b is equals to 5.

if a > b: is called if statement or control flow statement. Here, 10 > 5 is true so code inside if block will be executed. 

so, result is The largest number is 10

Example if..else statement

An "if else statement" is written by using the if  and else keyword.

a = 5

b = 6

If a>b:

       print(“The largest number is”, a)

else:

      print(“The largest number is”, b)

In the above example, a and b are two integer variables where a is equals to 5 and b is equals to 6.

if a > b: is called if statement or control flow statement. Here, 5 > 6 is false so code inside else block will be executed. 

So, Result is The largest number is 6.

elif 

"elif" is used when more than two conditions are checked, like -

a = 10

b = 10

If a > b:

      print(“The largest number is”, a)

elif b > a:

      print(“The largest number is”, b)

else:

      print(“Both are equal”)

In the above example, a and b are two integer variables where a is equals to 10 and b is equals to 10.

if a > b: is called if statement or control flow statement. Here, 10 > 10   is false so a > b and b > a both are false so code inside else block will be executed. 

So, Result is Both are equal.

One line way(shorthand way)

>>> a = 5

>>> b = 6

>>> if a>b:print(“number a is largest”)

>>> print(“the largest number is”, a) if a>b else print(“the largest number is”, b)

How to combine logical operator using “and”

"and" is used to combine logical operator as per given below syntax

>>> a = 5

>>> b = 6

>>> c  8

>>> if b==c and b>a:

           print(“both are true”)

As like above “or” is used to check when at least one condition is true.

bottom of page