Conditional statements allow us to branch execution based on the value of an expression.
expr is converted to bool as if by the bool() Constructor
>>> if True:
... print("It is true!")
...
It is true!
>>> if False:
... print("It is not true")
...
>>> if bool("hello"):
... print("Hello .. Thank you")
...
Hello .. Thank you
>>> if bool(""):
... print("Empty is not true")
...
>>>
Nested if inside else
>>> i=10
>>> if(i==11):
... print("i is 11")
... else:
... if(i==9):
... print("i is 9")
... else:
... print("i may be 10")
...
i may be 10
Whenever you find yourself with an else block containing a nested if statement , you should consider instead using Python's elif keyword, which is a combined else/if
>>> if(i==11):
... print("i is 11")
... elif(i==9):
... print("i is 9")
... else:
... print("i may be 10")
...
i may be 10
The expression need not to be boolean python explicity converts the expression to boolean
>>> if True:
... print("I am true")
...
I am true
>>> if "1":
... print("I am also true")
...
I am also true
>>> if "":
... print("I am not true")
...
>>> if "False":
... print("This is not an empty String")
...
This is not an empty String
>>>
It is similar to ternary operator ? in other languages
if expression is true a is returned else b is returned