Python If ... Else:
Python contains three keywords for checking conditions.
- if
- else
- elif
Logical conditions are used with if statements these conditions are:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
1. if
Example:
a = 30
b = 30
if b == a:
print("b is equal to a")
if b == a:
print("b is equal to a")
Output:
b is equal to a
Note that we have to give indentation after if statement which tell that the print statement is under if block otherwise it will be error.
2.else
The else keyword get executed if the preceding conditions is false.
Example:
a = 90
b = 33
if b > a:
print("b is greater than a")
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
print("a is greater than b")
Output:
a is greater than b
Here the else statement get executed.
3. elif
The elif keyword is a way of saying that "if the previous conditions were not true, then try this condition".
Example:
a = 90
b = 90
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
b = 90
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a and b are equal
4. Nested if:
It is a ladder of if statement or we can say multiple if statement.
It is written as:
Example:
a = 90
b = 90
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
elif a > b:
5. Short hand if:
4. Nested if:
It is a ladder of if statement or we can say multiple if statement.
It is written as:
Example:
a = 90
b = 90
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
elif a > b:
print("a is greater than b")
Output:
a and b are equal
Example:
a = 90
b = 90
if a = b: print("a is equal to b")
6. Short hand if-else:
Example:
print("A") if a < b else print("B")
7. if-else using (and) and (or):
Example 1:
if a > b and c > a:
print("Both conditions are True")
print("Both conditions are True")
Here the print block will execute only when a>b and c>a are true.
Example 2:
if a > b or a > c:
print("At least one of the conditions is True")
print("At least one of the conditions is True")
Here the print block will execute only when one of the condition is true.
0 Comments