If statement in Python Programming | Python Programming

If statement in Python: If statement is one of the easiest concepts of control flow statements. This statement is very helpful, while or when we need to make decisions, based on our problem what to do next.
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 a condition is False.

We will learn in detail about these flow control statements in detail.

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

  • if
  • if-else
  • if-elif
  • if-elif-else
  • nested-if

Let’s discuss all above statements in detail one by one:- First one is “if”

(i). If statement: The execution of an if-statement is very normal and easy to understand. If statement only returns the given result or output only when the condition is true. But it does not return any result or output if a condition is false. For reference, you can see the below-given flow chart.

if statement in python

Syntax

# if statement example

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

# output
# True

The above given example is the easiest example to understand if-statement. But the point to be noted that, this statement is helpful if the condition is True, ie. it returns result only if the condition is true but if the condition is false then it will not return any result.

Example 1:

# if statement example 

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

# output
# It will not show any result or output as the condition is False.

Important: How we know when our condition is false as it is not returning any result or output. If it is returning True when the condition is True why not it is returning False if the condition is False.  It is done by using an else conditional statement. Read this if-else guide to learn more…

Example 2: Write a program to check whether the given letter is vowel or consonant.

a = ['a','e','i','o','u']
x = 'o'
if x in a:
    print(x,"is vowel")

# output
# o is vowel

Explanation:

  • Here in this program, we are checking whether the given letter is vowel or consonant.
  • It will return result only if the letter is a vowel.
  • If the letter is consonant it will not return any result.
  • We can use an if-else statement, in case if we want to display result in both conditions whether the letter is vowel or consonant.

 

Other Control Flow Statements: