Python Core



Admission Enquiry Form


What is Python if-else statement?

There are some decision making statements in every language.By these statements we can run a particular block of code for a particular decision.
In Python, the decision making is done by following statements:

  1. If statement
  2. If-else statement
  3. if-elif statement

Indentation in Python

For the purpose of simplicity and ease ,python does not allow paranthesis for block level of if-else staement.Indentation is the most used part of the python language to declares the block of code.
Generally, four spaces are used to indent the statements .

Syntax of if statement

if expression:  
  statement
    

Example of if statement

n=int(input("Enter the number")) 
if n>0:  
    print("Number is positive")

Output:

          Enter the number 10
          number is positive       

if-else statement

In if-else statement there is one more block with if that is else block.The else block executes when condition is false.

Syntax of if-else statement

if expression:  
     statement
else:
    statement

Example of if-else statement

n=int(input("Enter the number")) 
if n>0:  
    print("Number is positive")
else:
    print("Number is negative")
     

Output:

          Enter the number -10
          number is negative       

if-elif statement

The if-elif statement used to check multiple conditions and executes the specific block on which the condition is true.

Syntax of if-elif statement

if expression:  
   statement
elif expression:
   statement
elif expression:
    statement
else:
    statement

Example of if-elif statement

n=int(input("Enter the number"))
if n>0:  
    print("Number is positive")
elif n<0:
    print("Number is negative")
else:
    print("Number is zero")       
    
     

Output:

          Enter the number 0
          number is zero