In Python there is only one conditional statement.
That is if-elif-else, conditional.
The syntax is fallow.
Indentation in Python.
Before we proceed further, its necessary to know about Indentation.
In Python indentation is very important.
Python code blocks are structured through indentation.
All statements with same indentation makes code block.
In Python code blocks have no explicit begin and end demarcation or curly braces.
Code blocks are identified by colon (:) delimiter and code indentation.
Conditionals, function definition, class definition, while, for loops etc….
use code blocks for program logic.
In Python indention is not just a style, its a must.
if [boolean-expression]: <true statements> else: <false statements>
There is no switch case in python like C,C++, or Java.
Let’s look at some conditional examples.
if-else branching examples.
Conditional check for two given numbers.
a,b = 0,1 if a == 0: print("a has a zero value") if b == 1: print("b has a non zero value") output: a has a zero value b has a non zero value
Check for truthiness
# assigning a None value to a a = None #None is a built in type if a: print("a has a value") else: print("a has no value") output: a has no value #if a : is same as if a == True:
Using if-elif-else block
We can use multiple elif blocks between if and else.
value = 40 if value > 50: print (" Greater than 50") elif value < 30: print ("less than 30") elif value < 40: print ("less than 40") else: print("Between 40 and 50")
Ternary operation in Python
With if-else statement, We can also have C-Style ternary operation in Python.
(a < b ? a : b)
a = 10 b = 5 print("True" if a < b else "False" ) output : False #return value can be assigned to a variable max_of_a_b = a if a > b else b print(max_of_a_b) output: 10