SELECTION STATEMENTS
LEARNING OBJECTIVES
At the end of this chapter students will be able to understand
Concept of flow of control
Selection/Conditional Statements:
if. . . . else
Nested if
Use of Conditional Expression
FLOW OF CONTROL
In a program, the execution of statements can be sequential, selective, or iterative.
Sequential Construct
It is the default flow of statements and causes execution of statements in a sequential or linear order.
Selection/Conditional Constructs
It means execution of statements on the basis of a condition. If the condition is true, one group of statements is executed otherwise another group of statements is executed.
Iterative/Looping Constructs
It means repetition of a set of statements depending upon a condition. The set of instructions are executed repeatedly till a certain condition is true.
SELECTION/CONDITIONAL STATEMENTS
The selection statement allows us to choose a set of instructions for execution depending upon the truth value of the expression.
The selection statements are also calledconditional statements or decision statements.
The selection statement in Python is: if statement
The various forms in which if statement exists are:
SIMPLE if statement
COMPOUND if (if. . . else STATEMENT)
COMPLEX if (if. . . elif . . . else LADDER)
NESTED if
SIMPLE if Statement
SYNTAX:
if conditional-expression:
Statement-block
If statement allows selection depending upon the outcome of a condition.
If the conditional expression evaluates to true, then the indented block of code is executed. If the condition is not true, then indented statements are skipped.
Statements which are outdented, are not a part of the if-else statement: They are always executed in the normal forward flow of statements, after the if.
EXAMPLE
Q WAP to input a number and display “POSITIVE” if the number is greater than 0.
num= int (input ('Enter a number'))
if num > 0:
print('positive')
OUTPUT
Enter a number56
positive
Enter a number-12
EXAMPLES OF TEST CONDITIONS
Let us have a look at some examples of test conditions
Test conditions
Explanations
if grade=='a':
print('You did well')
Comparing the value stored in variable grade with constant value 'a'.
if a>b:
print('a has more than b has')
comparing values of two variables
if x:
print('x is non-zero')
Testing truth value of a variable. If the value of the variable x is zero if evaluates to false. If the value of the variable x is non-zero if evaluates to true.
if x%2==0 and x>100:
print('great')
Here conditional statement is a compound expression. Two conditions are joined by the logical operator and. It evaluates to true if both the conditions are true.
x=10;
if x>100:
print('big number')
print('more than 100')
In this case, the last statement is outdented so only the first statement after if statement is included in the if statement. The second statement is not included in the if statement. Thus, second statement is always executed irrespective of the result of the conditional expression.
COMPOUND if (if. . . else STATEMENT)
Syntax:
if conditional-expression:
StatementBlockForTrueCondition
else:
StatementBlockForFalseCondition
If statement allows selection depending upon the outcome of a condition.
If the conditional expression evaluates to true, then the indented statement block immediately following if will be executed.
If the conditional expression evaluates to false, then the indented statement block following the else clause will be executed.
At a time, only one block of statements will be executed eitherStatementBlockForTrueCondition or StatementBlockForFalseCondition.
EXAMPLE
Q WAP to input a number and display "EVEN" if the number is even otherwise display "ODD".
num=int (input ('enter a number'))
if num%2 == 0:
print ('EVEN')
else:
print ('ODD')
OUTPUT
enter a number45
ODD
enter a number24
EVEN
COMPLEX if (if...elif ...else LADDER)
SYNTAX:
if conditional-expression1:
Statement Block-1
elif conditional-expression2:
Statement Block -2
....
....
....
....
else:
Statement Block-n
In the complex if, there is a ladder of multiple conditions presented by each if, all of these conditions are mutually exclusive.
Out of the multiple conditions only one of them will evaluate to true and then the statement block following that condition will be executed.
Once one of the conditional expressions become true all the conditions below it will not be evaluated (checked).
If none of the conditional expression becomes true then the statement block following the else statement are executed.
It is not mandatory to add an else at the end of the ladder.
Each of the code blocks in an if/elif-statement must be indented by the same amount.
EXAMPLE
Q WAP which accept number of week’s day (1-7) and print it’s equivalent name of week day (Monday for 1, ......, Sunday for 7).
day=int(input('Enter a number (between 1 and 7):'))
if day ==1:
print('Monday')
elif day ==2:
print('Tuesday')
elif day ==3:
print('Wednesday')
elif day ==4:
print('Thursday')
elif day ==5:
print('Friday')
elif day ==6:
print('Saturday')
elif day ==7:
print('Sunday')
else:
print('You entered a wrong number')
OUTPUT
Enter a number (between 1 and 7): 5
Friday
Enter a number (between 1 and 7): 9
You entered a wrong number
NESTED if
When an if statement is written inside the if or else clause of another if statement then it is known as nested if.
SYNTAX:
if conditional-expression1:
if conditional-expression2:
Statement Block -1
else:
Statement Block -2
else:
Statement Block-3
If the first conditional expression (ie conditional expression 1) is true, the control passes to the conditional expression 2. If the conditional expression 2 evaluates to true, the statement block 1 will be executed otherwise statement block 2 will be executed.
If the first conditional expression (ie conditional expression 1) is false, the conditional expression 2 will not be executed and control reaches to second else statement. As a result, statement block 3 will be executed.
EXAMPLE
Q WAP to print a message "Eligible for voting" if the nationality of the citizen is I (I for Indian) and age greater than or equal to 18, otherwise print "Not eligible".
nationality =input('Enter nationality - first letter only')
if nationality == 'i' or nationality == 'I':
age=int(input('enter age'))
if age >= 18:
print('eligible for voting')
else:
print('not eligible, age is less than 18')
else:
print('not eligible, nationality is not Indian')
OUTPUT
Enter nationality - first letter onlyI
enter age23
eligible for voting
Enter nationality - first letter onlyI
enter age12
not eligible, age is less than 18
Enter nationality - first letter onlyh
not eligible, nationality is not Indian
MORE EXAMPLES
if x>5:
if y<10:
print('hello')
else:
print('hai')
In this case, there are two if's. It is difficult to identify to which if the else should match. By default, the compiler will match the else with the immediate if. So, in this case, else matches the inner if.
VALUES
OUTPUT
x=4, y=5
No output (first condition is false)
X=6, y= 5
hai (first condition is true and second condition is false)
X=10, y=7
Hello ( both conditions are true)
if x>5:
if y<10:
print('hello')
else:
print('hai')
In this case, else matches the outer if.
VALUES
OUTPUT
x=4, y=5
hai (first condition is false)
X=6, y= 5
No output (first condition is true and second condition is false)
X=10, y=7
Hello ( both conditions are true)
if x>5:
if y<10:
print('hello')
print('world')
else:
print('hai')
In this case, both inner and outer if statements end when the first print statement (i.e. print('hello') is executed. After that the second print statement (i.e. print('world')) is executed. Now when the else statement is encountered, it will result as an error because it has no matching if. So, this code will result in an error. The error can be removed by enclosing the first two print statements in {}.
if x>5:
if y<10:
print('hello')
print('world')
if z==2:
print('amazing')
else:
print('Python')
In this case, else matches the third if.
VALUES
OUTPUT
x=4, y=5, z=2
worldamazing
(first condition is false thus second will not evaluate, third if condition is true)
x=4, y=5, z=5
worldPython
(first condition is false thus second will not evaluate, third if condition is false)
x=10, y=7, z=2
helloworldamazing
(All conditions are true)
x=10, y=17, z=2
worldamazing
(first condition is true, second is false, third is true)
x=10, y=17, z=4
worldPython
(first condition is true, second is false, third is true)
NOTE : The else statement is always paired with the most recent unpaired if.
CONDITIONAL EXPRESSIONS
SYNTAX
a if condition else b
First condition is evaluated, then either a or b is returned based on the Boolean value of condition. If condition evaluates to True a is returned, else b is returned.
It’s essentially a shorthand notation for if-statements that can be used directly within expressions.
EXAMPLE
num = eval(input("Enter a number"))
ans='Yes' if num>0 else 'No'
print(ans)
OUTPUT
Enter a number11
Yes
The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either 'Yes' or 'No' . It's equivalent to the following if statement:
num = eval(input("Enter a number"))
if num>0:
ans='Yes'
else:
ans='No'
print(ans)
Although not very flexible conditional expressions are usually shorter than the corresponding if/else-statements.
Comments
Post a Comment