PYTHON UNLEASH'D 04
HELLO LETS SEE CONDITIONAL STATEMENT IN PYTHON
As indentation plays major role in python. Indentation is used in place of brackets.
In conditional statements, we have colon which we have to use after is and else, at the end.
- if statement
- if-else statement
- nested if
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Unlike C++, we do not write else-if we write elif in python in if-else chain
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
In case of nested if the following if statement execute only if the s=above statements are true, else if comes to 'else block'.
WE HAVE SHORTHANDS ALSO FOR IF ELSE
var = 6
if(var > 5): print("greater")
print("hello") if var > 5 else print("no")
Ternary Operator
In C++, we have below ternary operator
(5 < 6)?b = "true": b = "false";
Here in python, we have if-else in ternary operator
- Each operand of the Python ternary operator is an expression, not a statement, that means we can’t use assignment statements inside any of them. Otherwise, the program will throw an error.
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
Shows good example of how we can use ternary operator with tuple, dictionaries and lambda function
We are pretty familiar with if-else so lets move to next new type of conditional statement, not definitely the new but here we have different name and keyword for that.
Also are you aware about 'pass' and when to use this?
Lets read about pass in next blog of this series.
Thanks for reading!
Top comments (0)