Tag Archives: if-else

Python: If-Else Statement


It is a conditional statement used for selection between two set of statements based on the evaluation of test condition. The statements inside the if block are executed only if the evaluated condition is true. Otherwise statements inside the else block are executed. As we have two set of statements to select based on the test condition, it is also called as Two-way selection statement.

Below is the syntax of if-else statement:

Python if-else statement

Example

	a=-10
	if(a>0):
		print("positive integer")
	else:
		print("Not a positive integer")

Output

Not a positive integer

In the if statement will evaluate condition and result as false then it will jump to else block then it will execute statement of else block.

Java : if-else-if Statement


The if-else-if statement is the decision-making statement, Use If the if-statement conditional statement execution result is false then control will reach to check conditions for an else-if statement. If the result is true, block associated with else-if statement will execute otherwise control will reach to else block. We can add multiple else-if statements consecutively.

Syntax:

if(test_expression)
{
   //execute your code
}
else if(test_expression n)
{
   //execute your code
}
else
{
   //execute your code
}

Note :
An if-else-if statement else is an optional clause. Below is the format without the else clause:

if (test-expression)
{
statement
}
else if (test-expression)
{
statement
}

See Also :

if-else-if Statement Example

public class IfStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0){
         System.out.println("a is positive number");
      }
	  if(a<0){
         System.out.println("a is negative number");
      }
	  else{
         System.out.println("a is zero");
      }
}

Output


a is positive number

Note :
The if-else-if statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example, the Below code is equivalent to the same as the above example and returns the same result.

public class IfElseIf{

   public static void main(String args[]){
      int a=20;

      if(a>0)
         System.out.println("a is positive number");
      else if(a<0)
         System.out.println("a is negative number or zero");
      else
         System.out.println("a is zero");

}

Recommendation :

  • For a better understanding of code always use curly braces ({}) with if, if-else-if or if-else statements.
  • It always creates confusion when more than one statement is in code.