Conditional Statements
A conditional statement is a statement that runs a command block only when certain conditions are met.
conditional statements are used to control or decide the flow depending on condition.
There are four types of conditional statements
1) If Statement
2) If Else Statement
3) Elif Statement
4)Nested If Statement
1) If Statement :-
If statement is a simplest conditional statement.
It is used when you need to print out the result when one of the condition is True or False.
Syntax -:
if(condition):
indented Statement Block
Example -:
X=input("Enter your name-:")
if (X=="RAJ"):
print (f" HELLO {X}")
Output-:
Enter your name-:RAJ
HELLO RAJ
Flowchart -:
2) If Else Statement -:
In If-Else statement, If statement checks the given condition is True or Not and if the given condition is True it will directly executes the indented block of code.
In Else statement it will executes the statement in Else block.
Syntax -:
if(condition):
Indented statement block for when condition is TRUE
else:
Indented statement block for when condition is FALSE
Example -:
A=int(input("Enter a first number-:"))
B=int(input("Enter a second number-:"))
if (A>B):
print (f" A IS GREATER")
else:
print (f" B IS GREATER")
Output -:
Enter a first number-:20
Enter a second number-:10
A IS GREATER
Enter a first number-:10
Enter a second number-:20
B IS GREATER
Flowchart -:
3) Elif Statement -:
Elif statement is used to check multiple conditions.
Syntax -:
if(Condition1):
Indented statement block for Condition1
elif(Condition2):
Indented statement block for Condition2
else:
Alternate statement block if all condition check above fails
Example -:
A=int(input("Enter a first number-:"))
B=int(input("Enter a second number-:"))
if (A>B):
print (f" A IS GREATER")
elif(B>A):
print (f" IS GREATER")
else:
print (f" BOTH ARE SAME")
Output -:
Enter a first number-:40
Enter a second number-:20
A IS GREATER
Enter a first number-:20
Enter a second number-:40
B IS GREATER
Enter a first number-:20
Enter a second number-:20
BOTH ARE SAME
Flowchart -:
4) Nested If Statement -:
If statement inside another if statement this is called nesting.
indentation is the only way to figure out the level of nesting.
Syntax -:
if (condition1):
Executes when condition1 is true
if (condition2):
Executes when condition2 is true
if Block is end here
if Block is end her
Example -:
N=int(input("Enter a year-:"))
if (N%4==0):
if (N%100==0):
if (N%400==0):
print (f" {N} IS A LEAP YEAR")
else:
print (f" {N} IS NOT A LEAP YEAR")
else:
print (f" {N} IS A LEAP YEAR")
else:
print (f" {N} IS NOT A LEAP YEAR")
Output -:
Enter a year-:2012
2012 IS A LEAP YEAR
Enter a year-:2014
2014 IS NOT A LEAP YEAR
Flowchart -:
Comments
Post a Comment