top of page

Python Bootcamp Day 30 Coding Exercises - 100 Days of Code by Dr Angela Yu

  • Writer: Unusual Accountant
    Unusual Accountant
  • Jan 9, 2022
  • 2 min read


Day 30.1 IndexError Handling


Issue

There is buggy code - looking through the list of fruits for an index that's out of range.


fruits = ["Apple", "Pear", "Orange"]
def make_pie(index):
    fruit = fruits[index]
    print(fruit + "pie")
make_pie(4)

Instructions


Use what you've learnt about exception handling to prevent the program from crashing.

When we try to pick something out of the list that doesn't exist, we 're going to print out the default output, which is jus Fruit Pie.



Solution

Try the code fruit = fruits[index] and if it fails, in the case of an IndexError, print("Fruit Pie"), otherwise (else), print(fruit + "pie")


fruits = ["Apple", "Pear", "Orange"]
def make_pie(index):
    try:
        fruit = fruits[index]
    except:
        print("Fruit pie")
    else:
        print(fruit + "pie")
make_pie(4)

Day 30.2 KeyError Handling


Issue

There is a KeyError from the block of code below and it's because when looping through every post inside the list and trying to get hold of total likes by adding the existing number to the number of likes in each post, it gives a KeyError. This is because some of the posts in the facebook_posts don't have any likes.


facebook_posts = [
    {'Likes': 21, 'Comments': 2},
    {'Likes': 13, 'Comments': 2, 'Shares': 1},
    {'Likes': 33, 'Comments': 8, 'Shares': 3},
    {'Comments': 4, 'Shares': 2},
    {'Comments': 1, 'Shares': 1},
    {'Likes': 19, 'Comments': 3}
]
total_likes = 0
for post in facebook_posts:
    total_likes = total_likes + post['Likes']

Instructions

Use exception handling methods, prevent the program from crashing.


Solution

I added a try statement to run the first line of code inside the for loop.

In the case of an exception error - KeyError, we can just pass, meaning it will skip and loop back to the next post.

It will loop through all the likes in the list and for the ones which have likes, it adds the number from the value of that key to our total number of likes. However, if we get a key error, we will just pass that key.


Below is the solution code.

facebook_posts = [
    {'Likes': 21, 'Comments': 2},
    {'Likes': 13, 'Comments': 2, 'Shares': 1},
    {'Likes': 33, 'Comments': 8, 'Shares': 3},
    {'Comments': 4, 'Shares': 2},
    {'Comments': 1, 'Shares': 1},
    {'Likes': 19, 'Comments': 3}
]
total_likes = 0
for post in facebook_posts:
    try:
        total_likes = total_likes + post['Likes']
    except KeyError:
        pass

print(total_likes)

 
 
 

Коментарі


Never Miss a Post. Subscribe Now!

I'm a paragraph. Click here to add your own text and edit me. It's easy.

Thanks for submitting!

© 2023 by Unusual Accountant

  • Grey Twitter Icon
bottom of page