If-else statements in Python
if statements are useful for comparing and if the provided if condition is true then the code inside the if block will be executed or else, the block of code will be skipped for execution. there is no curly{ } , braces for sub-block of code, so in python we use indentation, indentation is know as providing 4 spaces or more after functions or statements
simple if statement
syntax:
observe the syntax provided above,if the condition returns true than the two indented statements will be provided. Otherwise if used doesn't provide indention to the lines of code,which comes under the above if condition,those block doesn't has any condition and they will be executed whether the above condition is true or false
example:
if-else statement
if-else statements allows us to handle two types of results True or false of the given condition.
you can see the syntax above,if the condition is True then the if block statements will be executed,if the same above condition is False then the else block statements will excited by skipping if block statements. Indention is mandatory here ,if you failed to give indentation before line's of sub blocks like if or else block,then compiler will throw an error
example:
OUTPUT:
else block initiation should be exactly below the if block initiation,if this rule fails compiler throws an error
Nested if-else
nested if-else is called as if-else statement inside another if-else block
if-elif-else statement
instead of writing multiple if-else statements we can use if-elif statements .
now, the compiler checks conditions from condition 1,if any of the conditions are true , then respective elif block will be executed but , when all conditions are false then else block will be executed .if there are multiple conditions are True ,then the first occurrence of True, that block will be executed and loop breaks.
example: