Module2-Decision Structure
Module2-Decision Structure
Decision Structures
Forming Conditions
if statements:
if - statement is one of the simplest forms of the decision control
statement. It executes a set of statements conditionally, based on the
value of a logical expression.
Syntax:
if expression :
statement_1
statement_2
....
statement_n
If the condition is True, then the statement or code of block
corresponding to it is executed. The flowchart is given as shown below:
Syntax:
if expression :
statement_1
statement_2
....
else :
statement_3
statement_4
.…
Example1:
number1 = 20
number2 = 30
if(number1 >= number2 ):
print(“number 1 is greater than number 2”)
else:
print(“number 2 is greater than number 1”)
Inline-if-Statement:
An inline statement is a convenient form of representing a if-else
statement. This is known as ternary operator.this statement allows one to
execute conditional if statements in a single line.
Syntax: expression1 if condition else expression2
If the condition is True, then expression1 is executed, otherwise
expression2 is executed
Syntax:
expression1 if condition1 else expression2 if condition2 else
expression3
If the condition1 is True, then expression1 is executed. If the
condition1 is False, then condition 2 is executed. If the condition2 is True,
then expression2 is carried out, otherwise if condition False, expression3
is returned.
Example:
scoreMark = int(input(“Enter entrance exam mark:”))
Cutoff= 400
Admission = False if (scoreMark < Cutoff) else True
Print(admission)
Output:
Enter entrance exam mark: 325
False
If - elif statement:
Syntax:
if condition-1:
statement 1
elif condition-2:
statement 2
…
elif condition-n:
statement n
else:
else-statement
Example:
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
Output:
Admin
Editor
Guest
Wrong entry
Example:
1. Python program for grade allocation can be done using if-elif
statement
2. Python program should start with obtaining the height and weight of
the person and should obtain BMI of the person.
Syntax:
if condition_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block
Example1:
num1 = int( input())
num2 = int( input())
if( num1>= num2):
if(num1 == num2):
print(f'{num1} and {num2} are equal')
else:
print(f'{num1} is greater than {num2}')
else:
print(f'{num1} is smaller than {num2}')