Conditional statements in Python: -
Python codes execute serially
by default, in which statements are executed one after
the next.
If one needs to skip some statements, execute a
series of statements repetitively, or choose between alternate sets of
statements to execute.
For this use control structures.
A control structure controls the flow of
statement execution in a program.
It is also known as decision statements.
These are various types: -
1.
Simple if statement
2.
if-else Statement
3.
if-elif-else Statement.
4.
Nested if Statements
1. Simple if statement
Syntax:-
if(condition):
indented
Statement Block
The block of lines indented after the colon (:) will be executed whenever the condition is TRUE.
Colon (:
) separates
the condition from the executable statements after the evaluation of the
condition (the bracket ( )
is
not used)
Example:-
Num = 5 If(Num < 10): print(“Num
is smaller than 10”) print(“This statements will always be executed”) |
Output:
Num is smaller than 10.
Example:
a = 7 b = 0 if(a): print(“true”) |
Output:
true
Example:
if (‘python’ in [‘Java’,
‘python’, ‘C#’]): print(“true”) |
Output:
true
2. if-else Statement
syntax:
if(condition):
Indented statement block
for when condition is TRUE
else:
Indented statement block
for when condition is FALSE
Example:
a = 7 b = 0 if(a > b): print(“a
is greater than b”) else: print(“b
is greater than a”) |
Output:
a is greater than b
3. if-elif-else Statement
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
or
elif Ladder
This statement is used to test multiple expressions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and third elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
num = 10
if (num == 0):
print(“Number is Zero”)
elif (num > 5):
print(“Number is greater than 5”)
else:
print(“Number is smaller than 5”)
Output:
Number is greater than 5
Example:
my_marks = 89
if (my_marks < 35):
print('Sorry!!!, You are failed in the exam')
elif (my_marks < 60): print('Passed in Second class')
elif (my_marks > 60 and my_marks < 85): print('Passed in First class')
else:
print('Passed in First class with distinction')
Output:
Passed in First class with distinction
4. Nested if Statements
When using an if statement inside another if statement, called nesting if.
Also use this concept for if, if-else, and even if-elif-else statements combined to form a more complex structure.
0 Comments