Skip to content

Instantly share code, notes, and snippets.

@ahmad-ali14
Last active September 20, 2020 14:49
Show Gist options
  • Save ahmad-ali14/3f7498369bf19d2371b58532e91cfcf4 to your computer and use it in GitHub Desktop.
Save ahmad-ali14/3f7498369bf19d2371b58532e91cfcf4 to your computer and use it in GitHub Desktop.
"""
Describe the difference between a chained conditional and a nested conditional. Give your own example of each. Do not copy examples from the textbook.
Well, chained conditionals are usually at the same level, that means we have only one level of branching _main_ >> ( if - elif -else)
While the nested conditionals contain multiple levels of branching, __main__ >> first_level of branching ( if >> second_level_of_branching( if >> third_level … -elif-else ) - elif - else )
"""
# example of chained condition:
if morning:
eat_breakfast()
elif afternoon:
eat_lunch()
else:
do_not_eat()
# Example of nested conditions:
if morning:
switch_off_lights()
if someone_home:
if he_is_awake:
switch_on_TV()
if he_is_sleeping:
no_noise()
else:
if window_brokes:
call_the_cops()
else:
stay_alarmed()
if evening:
if someone_home:
swich_on_lights()
else:
swich_off_lights()
"""
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.
There are lots of ways to simplify nested conditionals, one of them is using logical operators or maybe refactor your code to avoid the use of all these nested conditions.
"""
# Let’s modify the previous nested conditions from the previous example:
if morning:
swich_off_lights()
if morning and someone_home and he_is_awake:
swich_on_TV()
if morning and someone_home and he_is_sleeping:
no_noise()
if morning and not someone_home and window_broke:
call_the_cops()
if morning and not someone_home and not window_broke:
stay_alarmed()
if evening and someone_home:
switch_on_lights()
if evening and not someone_home:
switch_off_lights()
"""
You can notice how nested conditions are hard to read compared to the simplified version using the logical operator, although my code can still be simplified more.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment