A Conditional Statement Having Multiple Alternative Branches Is Called A Chained Conditional
A Conditional Statement Having Multiple Alternative Branches Is Called A Chained Conditional
A conditional expression that has been nested can be found in one of its branches. As an
illustration, consider
<<<>< # After entering the following variables, the software that follows shows the outcome
of a football match:
H=3 # regular-time home team time Regular time of A=3 #away team In the event of a draw in
regular time, H2=0 #home team extra time A2=3 #away team extra time (in the event that
regular time ends in a tie) #home team penalty shootout P1=0 P=2.
nested conditional appears in one of the branches of another conditional statement. Examples
are
as follows;
>>> # The following program displays the winner of a football match after the
following variables have been input:
H=3 # home team regular time A=3 # away team regular time H2=0 # home team extra time(in
case of a draw in regular time) A2=3 # away team extra time(in case of a draw in regular time)
P1=0 # home team penalty shootout P2=2 # away team penalty shootout
if H > A: print('Home team Wins!') elif H2 > A2: print('Home team wins after extra time!')
elif P1 > P2: print('Home team wins on penalties') elif H < A: print('Away team Wins!') elif
H2 < A2: print('Away team wins after extra time') elif P1 < P2: print('Away team wins on
penalties') elif H==A: print('Extra time!')
else: print('Match Cancelled!')
>>>
points=3000 # credits acquired in the gaming platform cash=300 # money in the user's gaming
account.
if points>1000: print('Your points plus $50 will buy the Game') if cash>=50:
print('Purchase approved!') else: print('You need to deposit money into your account') else:
print('Purchase impossible')
by changing the variables (points and money) one gets different output
statements.
Your points plus $50 will buy the Game Purchase approved! >>>
Question 2
Deeply nested conditionals can become difficult to read. Describe a strategy for avoiding nested
conditionals. Give your own example of a nested conditional that can be modified to become a
single conditional, and show the equivalent single conditional. Do not copy the example from
the textbook.
Ans.
Logical operators can be used to simplify a nested conditional into a single conditional. In the
example below I have used the ‘and’ operator to simplify the nested conditional.
Example.