Krivalar Tutorials 
Krivalar Tutorials

Python if, elif, if else Syntax & Example



<Output    if-else Statement >







In our real life, we have to take various decisions and if one fails, we may choose an alternative to reach our goal. Similarly, there may be the situations in real life programming where we want to check the condition and change the execution of the program accordingly. The behavior of the program is changed by using the conditional statement. The simplest form of a conditional statement is an if statement.

if Statement

  • The if statement is used to check the condition or Boolean expression.
  • If the condition is True, a block of code will be executed. Otherwise, python will skip the block of codes.
  • The if statement begins with the keyword if.
  • The if statement consists of a header (condition) followed by a block of codes.
  • The condition must follow the word if.
  • The condition is a Boolean expression that checks whether or not the block of codes is to be executed.
  • The block consists of one or more statements.
  • The whole block must be indented with a same number of spaces.

Flow Chart



Syntax of Python if Statement

if(expression):
    Statement_1
    Statement_2...
  • Where, the condition is the Boolean expression that returns either True or False.
  • If the condition is True, then indented statements will be executed.
  • If the condition is False, nothing will happen.
For example
>> A=10
>> if((A%2)==0):
...     print('The value A is even')
...
The value A is even
>>

While executing the above if statement, when the condition((A%2)==0)is True, the following print statement will display the text on the console.

Suppose the block contains one statement, that statement will be written on the same line as an if condition.

For example:

>> A=10
>> B=5
>> if(A>B):
...   print('The A is greater than B')
...

The A is greater than B

The above example can also write as follows.

>> A=10
>> B=5
>> if(A>B): print('The A is greater than B')
...
The A is greater than B

But, the above code can not write as follows.

>> A=10
>> B=5
>> if(A>B):
    print('The A is greater than B')

While executing the above code, you will get an error.

>> A=10
>> B=5
>> if(A>B):
... print('The A is greater than B')
  File "<stdin>", line 2
    print('The A is greater than B')
    ^
IndentationError: expected an indented block
>>

<Output    if-else Statement >





















Searching using Binary Search Tree