Python If Statements

The Python if statement is a statement which is used to test specified condition. We can use if statement to perform conditional operations in our Python application.

The if statement executes only when specified condition is true. We can pass any valid expression into the if parentheses.

There are various types of if statements in Python.

  • if statement
  • if-else statement
  • nested if statement

 

Python If Statement Syntax

  • if(condition):  
  •    statements  

 

 

Python If Statement Example

  • a=10  
  • if a==10:  
  •         print  “Welcome to Letuslearn”  

Output:

Welcome to Letuslearn

 

Python If Else Statements

The If statement is used to test specified condition and if the condition is true, if block executes, otherwise else block executes.

The else statement executes when the if statement is false.

Python If Else Syntax

  • if(condition):  False  
  •              statements  
  •     else:   True  
  •               statements  

 

 

Example-

  • year=2000  
  • if year%4==0:  
  •     print  “Year is Leap”  
  • else:  
  •     print “Year is not Leap”  

Output:

Year is Leap 

Python Nested If Else Statement

In python, we can use nested If Else to check multiple conditions. Python provides elif keyword to make nested If statement.

This statement is like executing a if statement inside a else statement.

Python Nested If Else Syntax

  • If statement:  
  •     Body  
  • elif statement:  
  •     Body  
  • else:  
  •     Body

 

Python Nested If Else Example

  • a=10  
  • if a>=20:  
  •     print “Condition is True”  
  • else:  
  •     if a>=15:  
  •         print “Checking second value”  
  •     else:  
  •         print “All Conditions are false”  

 

Output:

All Conditions are false.