CS1101 Unit 3 Discussion
CS1101 Unit 3 Discussion
10
1. Describe the difference between a chained conditional and a nested conditional. Give your own example of each.
A chained conditional is basically when you use an if/elif/else flow control and they are all indented on the same level.
They are also useful in situation where a condition can have different outcome/possibility. Whereas, a nested
conditional is where another conditional statement is place within a branch of an already existing conditional statement
which forms a nested shape, i.e. you are placing another if statement in another if statement which can create a much
more complicated computation.
chained conditional example
def discounter(price):
if price < 50:
savings = price * .2
print(f'You are saving ${savings}')
elif price > 50:
savings = price * .15
print(f'You are saving ${savings}')
discounter(price)
else:
print("You met a broken bridge and could not continue your hunt. Game
Over!! ")
treasure_hunt(direction)
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.
Response:
One strategy that we can used to avoided nested conditional is to use logical operators (and, or, not) which would
make our code much flexible. Thus, reducing the number of conditional statements needed as can be seen below
Nested conditionals example
num = int(input('enter the number you want to compare '))
if num % 2 == 0:
if num % 3 == 0:
print("This number is a multiple of 2 and 3")
else:
print("this number isnt a multiple of 2 and 3")
References
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press.