If, elif, else Statements

if, elif, else Statements

if statement:

- An if statement is written by the if keyword.

- An if statement is commonly used in these mathematical conditions:
  • a == b -    Equal
  • a != b -     Not Equal
  • a < b -      Less than
  • a > b -      Greater than
  • a <= b -    Less than or equal to
  • a >= b -    Greater than or equal to



Note: In the above code, we use the two variables a and b and use the if condition to print “a is greater than b”, we know 100 value of a is greater than 50 value of bif statement is true, so python will return “a is greater than b”.


if Statement without Indentation:

- Indentation is mandatory in if statement.

- Without indentation python will raise an error.


Output:



elif statement:

- If the previous if condition is not true, then try elif condition.

- An elif statement is written by elif keyword.



Note: In the above code, a is equal to b, we know if condition is not true but elif condition is true, so python will return “a is equal to b”.


else statement:

- An if and elif condition is not true then try else condition.

- An else condition is written by else keyword.



Note: In the above code, b is greater than a, we know if condition and elif condition is not true but else condition is true, so python will return “b is greater than a”.


if, else statement without elif:



Note: In the above code, a is not greater than b, we know if condition is not true but else condition is true, so python will return “a is not greater than b”.

Comments