If-else statement in Python Programming | Python Programming

If-else Statement in python: If-else statement is also one of the most easiest concept of control flow statements. This statement is very helpful, while or when we need to make decision based on our problem what to do next(in our life). The same type of problem arises sometimes in our programming also where we have to execute our code based on these decision making statements.

Let’s suppose we take an example: We want to print some message “Yes” or any statement when the condition is True and “No” when the condition is False.

We will learn about these flow control statements in detail.

Also, there are other control statements are also there, These are given below:-

  • if (already discussed)
  • if-else
  • if-elif
  • if-elif-else
  • nested-if

Let’s discuss all the above statements in detail one by one:- The first one is “if”, which we have discussed already (if-statement), now we discuss if-else:

(i). If-else statement: The execution of the if-else statement in python is very normal and easy to understand. If-else statement returns the given result or output only when the condition is true. But if the condition is False returns the result or output False/statement. For reference, you can see the below-given flow chart.

if-else-statement-in-python

Syntax

#if-else statement example

x = 23
if(x==23):
    print("True")
else:
   print("False")

# output
# True

The above given example is the easiest example to understand the if-else statement. The only difference between the if and the if-else statement is that if-statement only shows the output when the condition is True and does not show any output when a condition is False. But if-else returns output in both conditions whether the condition is True or False.

Example:

#if statement example 

x = 22 
if(x==23):
   print("True") 
else:
   print("False")

# output
# False
//It will return output as False.

Note: The only difference between the if and the if-else statement is that the if-statement only shows the output when the condition is True and does not show any output when a condition is False. But if-else returns output in both conditions whether the condition is True or False.

Example 2: Write a program to print the greater between two numbers.

Hint 1
a = 34
b = 30
a is greater

Hint 2
a = 25
b = 30
b is greater

a = 34
b = 30
if ( a > b ):
    print("a is greater")
else ( b > a ):
    print("b is greater")

# output
# a is greater

 

Other Control Flow Statements: