Operator and If-Else
Operator and If-Else
Python indentation
Python indentation uses to define the block of the code. The other programming
languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation. Whitespaces are used as indentation in Python.
Indentation uses at the beginning of the code and ends with the unintended line. That
same line indentation defines the block of the code (body of a function, loop, etc.)
Generally, four whitespaces are used as the indentation. The amount of indentation
depends on user, but it must be consistent throughout that block.
The if-else statement
The if-else statement provides an else block combined
with the if statement which is executed in the false case of
the condition.
If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.
The elif statement
The elif statement enables us to check multiple conditions
and execute the specific block of statements depending
upon the true condition among them. We can have any
number of elif statements in our program depending upon
our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement
in C. It must be succeeded by an if statement.
The syntax of the elif statement is given below.
Python nested IF statements
In a nested if construct, you can have
an if...elif...else construct inside
another if...elif...else construct.
Example 1:
# Python program to demonstrate
# nested if statement
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Example 2:
Syntax
The syntax of the nested if...elif...else construct may be −
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"