Advertisement
Mars83

8-3

Oct 9th, 2011
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 8.3
  6.    Rewrite the guardian code in the above example without two if statements.
  7.    Instead use a compound logical expression using the and logical operator
  8.    with a single if statement.
  9. """
  10.  
  11. # test.txt is equal to mbox.txt, but added following 3 lines somewhere:
  12. """
  13. >>> The next line fails with the original code:
  14. From xyz
  15. >>> because of there are more than one, but less than two words...
  16. """
  17.  
  18. ''' Main '''
  19. try:
  20.     fhand = open('test.txt')
  21. except:
  22.     print("File not found!")
  23.     exit()
  24. week = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
  25. count = 0
  26. for line in fhand:
  27.     words = line.split()
  28.     # print('Debug:', words)
  29.     if len(words) >= 3 and words[0] == 'From' and words[2] in week[:]:
  30.         try:                # Additional guard
  31.             print(words[2])
  32.             count += 1      # counts the interesting lines
  33.         except IndexError:
  34.             continue
  35. print("There are " + str(count) + " interesting lines.")
  36. try:
  37.     fhand.close()
  38. except:
  39.     exit()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement