0

I am getting an error saying "print('The person who sent the most emails is:',max_email_sender)" and "NameError: name 'max_email_sender' is not defined" and I know its because of my declarations that are within the try/catch block but im not sure how to rearrange it so the code can work. I tried to declare some of them outside of it but still ran into some problems

try:
   file = 'm.txt'
   file_open = open(file)
   d_dict = dict()
   max_email_sender = None

   for line in file_open:
      line = line.strip()
      if line.startswith('From:'):
        emails_sent = line[5:].strip()
        count_emails = d_dict.get(emails_sent,0)
        count_emails += 1
        d_dict[emails_sent] = count_emails
       if max_email_sender == None:
           max_email_sender = emails_sent
       elif d_dict[emails_sent] > d_dict[max_email_sender]:
           max_email_sender = emails_sent
except (AssertionError, FileNotFoundError) as e:
print(e)

print('The person who sent the most emails is:',max_email_sender)
print('The number of emails sent is:',d_dict[max_email_sender])
hannah
  • 195
  • 1
  • 12
  • Add your last two calls to `print` to an `else:` block so that they are only run if no errors were raised – Iain Shelvington Apr 14 '21 at 01:29
  • 1
    Does this answer your question? [What is a good way to handle exceptions when trying to read a file in python?](https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python) – drum Apr 14 '21 at 01:36
  • The code you've posted won't even run. Double check your indentation, as it's significant in Python – Silvio Mayolo Apr 14 '21 at 03:14

0 Answers0