While programming sometimes you need to take some decisions. You need to test some condition: true or false. In Python there are various types of statements for this. Some of them are given below.
- If Statement
- If Else statement
- Nested If statements
- If-elif ladder.
if condition: #some statement here if condition is true
i=10 if (i==10): print("value of i is 10")
value of i is 10
If Else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
if condition: #some statement if true else: #some statement if false
i=11 if(i<10): print("i is smaller than 10") else: print("i is greater than 10")
i is greater than 10
The block of code following the else statement is executed as the condition present in the if statement is false after call the statement which is not in block(without spaces).
Nested If Else Statements
A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement
if condition: //code to be executed if condition: //code to be executed
i=10 if(i==10): if(i<15): print("i is smaller than 15") else: print("i is greater than 15")
i is smaller than 15
If Else Ladder( If Elif)
The if-else-if ladder statement executes one condition from multiple statements.
if condition1: //execute the statement if condition1 is true elif condition2: //execute the statement if condition2 is true elif condition3: //execute the statement if condition3 is true .. else: // execute the statement if all the conditions are false
i = 20 if (i == 10): print ("i is 10") elif (i == 15): print ("i is 15") elif (i == 20): print ("i is 20") else: print ("i is not present")
i is 20