Python IF Else
Python Conditional statement can be executed using the if else statements.
If the condition given in if block is true then it will run the body of the block else it will check and run the next block.
You might be wonder why there is a space at the beginning of a print statement and what is the use of that. Well this are python indentation a very important topic from the python syntax point of view.
Python Indentation
Python Indentation are the white space given at the beginning of the body of block of code.
we should be keep certain things in mind while giving indentation, let's discuss them.
We could decide how much space we can give at the beginning of the line. But generally, we give 4 space at the beginning (Tab Space). Even one will do.
Python will throw an error if we don't give space at the beginning of the line.
Indentation should be same for each line inside a single block of code.
IF Else Syntax
if condition:
print("statement1")
elif condition:
print("statement2")
elif condition:
print("statement3")
elif condition:
print("statement4")
else:
print("statement5")
Logic of IF Else
-
Logic of IF Else is quite simple. You have to start with the if block which is a mandatory block and you will give some condition and if the condition is satisfied then it will print the given statement
-
else it will move to the next block which could be either else part or elif part which is optional.
-
you can have as many elif blocks between if & else block as you want.
-
Code will check line by line each condition and once the condition is true it will print the respective statement and code gets terminated and it won't go further.
-
you can even choose to have only if block in your code and don't have else or elif block.
Short hand IF Else
-
We can write our if else code in a single line. It is also knows as ternary operators.
-
Ternary operators are nothing but writing codes in single line and getting some output.
Nested IF Else
-
Nested if else statement means inside if else blocks we are going to have more if else blocks.