Python if..else Statement
Before learning if...else statment we
have to understand
about Comparison Operators.
| Operator | Description | Example |
|---|---|---|
| == | Checks if the value of two operands are equal or not, if yes then condition becomes true. | (A == B) is False. (A==A) is True. |
| <> | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. | (A <> B) is True. |
| > | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (5 > 10) is False. |
| < | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (5 < 10) is True. |
| >= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (5 >= 10) is False. |
| <= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (5 <= 10) is True. |
if..else statement is all about
decision making.
Sructure
if (condition) :
body 1
else:
body 2
We can make an assumption(condition) with the if statement, and use the else statment to give an option of what to do if it didn't satisfy the above condition.
As you can identify in the abve code, identation(spacing) is important when using if...else statement and make sure : (colon) is there after if/else condition.
We can also use mutiple if
statements with-in
the same if statement.
We have used Type convertions here.
"elif" function
As you can observe in the above example
when we increase the
number of conditions, the code moves more to "right". To avoid that we can use "elif".
The above example can be written as follows.