Advertisement
Mars83

7-3

Oct 7th, 2011
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 7.3
  6.    Sometimes when programmers get bored or want to have a bit of fun, they add
  7.    a harmless Easter Egg to their program
  8.    (en.wikipedia.org/wiki/Easter_egg_(media)).
  9.    Modify the program that prompts the user for the file name so that it
  10.    prints a funny message when the user types in the exact file name
  11.    ’na na boo boo’. The program should behave normally for all other files
  12.    which exist and don’t exist. Here is a sample execution of the program:
  13.    python egg.py
  14.    Enter the file name: mbox.txt
  15.    There were 1797 subject lines in mbox.txt
  16.    python egg.py
  17.    Enter the file name: missing.tyxt
  18.    File cannot be opened: missing.tyxt
  19.    python egg.py
  20.    Enter the file name: na na boo boo
  21.    NA NA BOO BOO TO YOU - You have been punk'd!
  22.    We are not encouraging you to put Easter Eggs in your programs -
  23.    this is just an exercise.
  24. """
  25.  
  26. ''' Functions '''
  27. def enterFileName():
  28.     """
  29.    The user has to enter a filename.
  30.    Returns fileName
  31.    """
  32.     fileName = None
  33.     while fileName == None:
  34.         # Enter filename
  35.         try:
  36.             fileName = input("Enter the filename: ")
  37.         except:
  38.             print("Invalid input!")
  39.             continue
  40.     return fileName
  41. # End of enterFileName()
  42.  
  43. ''' Main '''
  44. file = None
  45. subjectCounter = 0
  46. fileName = enterFileName()
  47.  
  48. try:
  49.     file = open(fileName, 'r')      # Open file
  50. except:
  51.     if fileName == "na na boo boo":
  52.         print("NA NA BOO BOO TO YOU - You have been punk'd!")
  53.     else:    
  54.         print("File cannot be opened: " + str(fileName))
  55.     exit()
  56. if file != None:
  57.     try:
  58.         for line in file:           # Read file content
  59.             if line.startswith("Subject: "):
  60.                 subjectCounter += 1
  61.     except:
  62.        print("Error on reading file content!")
  63.     print("There were " + str(subjectCounter) + " subject lines in " +
  64.           str(fileName))
  65.     try:
  66.         file.close()                # Close file
  67.     except:
  68.         print("File could not be closed!")
  69.         exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement