This decision making statement works based on the condition. That is, if the output of the condition is true, a block of code is executed. If the output of that condition is false, another block of code executes.
There are total 4 decision making statements in Python which are:-
If statement
If Else Statement
If Elif Else Statement
Nested if statement
If statement
#Syntax:
If(condition)
Statement 1
Statement 2
Curly brackets are used in other programming languages but in python indentation is used instead of curly brackets. Indentation is the provision of ample white space before the beginning of a statement.
x=10
if(x==10):
print("It is equal")
print("If Block End")
''''
output:
It is equal
If Block End
''''
Description:-
x=10 -> Here variable x value 10 is saved.
if(x==10):
Here the condition is checked and we get True output. Because (x==10) the variable x has a value of 10 so the condition is True. Since the condition is True, the print statement 'It is equal' inside the if block is executed. After that it exits the if block. At the end the print statement 'if block end' is printed.
x=-2
if(x>0):
print("Positive number")
if(x<0):
print("Negative number")
''''
output:
Negative number
''''
Description:-
A memory is created for the variable x and the value -2 is stored in it. Next two if condition are given in that python program. The first if condition is checked.
if(x>0) -> if(-2>0) -> False
Since the first if condition gives us false output, we skip this if statement and go to the second if statement.
if(x < 0) -> if(-2 < 0) -> True
Since the second if condition is checked and gives us the output True, the print statement "Negative Number" inside this if statement is printed in the output.
If Else statement
If else means that the condition in the If statement is checked and if the output is TRUE, the statement in the If block is executed. If the output is FALSE then the statement in the else block will be executed.
# if else Syntax
if(condition):
statement 1
statement 2
statement 3
.
.
.
statement n
else
statement 1
statement 2
statement 3
.
.
.
statement n
Programme:
age=15
if(age>=18):
print("Eligible for vote")
else:
print("you are not eligible for vote")
''''
output:
You are not eligible to vote
''''
Description:-
A value of 15 is saved in the age variable. Next, the condition in the if statement is checked.
if(age>=18) -> if(15>=18) -> FALSE
Condition is checked and FALSE OUTPUT is received, so the message “you are not eligible for vote” in the else block is displayed on the output screen.
This is how the if….else statement works.