Python Tutorial

Python Conditional Statement

What is Conditional Statement in Python?

Conditional statements are another name for decision-making statements. When we wish to run a block of code based on whether a condition is true or false, we use those statements. 

Python has six conditional statements:

1. If statement

2. If else statement

3. Nested if statement

4. If-elif-else ladder

5. Shorthand if statement

6. Shorthand if-else statement

If Conditional Statement in Python

If statement is most commonly employed as a conditional statement. 

Syntax:

if(condition):        

#if statement  

Code:

x = 10  

y = 20  

if x

print("x is less than y")

  

Output:

x is less than y

if-else statement

If else is a conditional statement. If a particular condition is true/false, the statement says so. True indicates that the "if" expression is applied to the output. False indicates that the "else" sentence is applied to the output.

Syntax:

if(condition):    

    # if statement   

else:    

    # else statement  

Code: 

x = 10  

y = 20  

if x==y:  

print("x and y are equal")  

else:  

   print("x and y are not equal")  

Output:

x and y are not equal

if-elif-else statement in Python

Elif is a shorthand for else if conditionals. The elif statement in Python has one or more criteria.

Syntax:

if(condition):  

   # if statement  

elif(condition):  

   # elif statement  

else:  

   # else statement  

Code:

a = 10  

b = 10  

if a < b:  

   print("a is greater than b")  

elif a == b:  

   print("a and b are equal")  

else:  

  print("b is greater than a")  

Output:

a and b are equal

Python Nested if statements

In Python, the use of ‘if’ statements inside other ‘if’ statements is called a nested if statement.

Syntax:

if(condition):  

     if(condition): 

         # if statement    

Code:

x= 1001  

if x> 100:  

   print("Above 100")  

  if x > 1000:  

    print("and also above 1000")  

Output:

Above 100 
and also above 1000

QUIZ

quiz-img
Did you find this article helpful?