0

Here is my code:

print "Note: Your file is available now."
viewYourFile = raw_input("\nDo you wish to view this file now? ")

if viewYourFile == 'Y' or 'y':
    fo = open('messages.txt', 'r+')
    #Read whole file into data
    data = fo.read()
    print data
    # Close the file
    fo.close()
elif viewYourFile == 'N' or 'n': 
    print "Thank you!"
else:
    print "Didn't recognize user input"

When I type in 'n' the text file still opens. If the user types in 'N' or 'n' I want the script to move on without printing the text into the terminal.

I can't spot anything obvious that I've done wrong. Can someone take a second look for me? Many thanks.

BubbleMonster
  • 1,366
  • 8
  • 32
  • 48

3 Answers3

3

if viewYourFile == 'Y' or 'y': always evaluates to True since the second condition 'y' is always True.

>>> bool('y')
True
>>> bool(False or 'y')
True

Use if viewYourFile in ('Y', 'y'): instead.

Also, instead of closing the file manually, use with context manager. Here's the resulting code:

print "Note: Your file is available now."
viewYourFile = raw_input("\nDo you wish to view this file now? ")

if viewYourFile in ('Y', 'y'):
    with open('messages.txt', 'r+') as fo:
        data = fo.read()
elif viewYourFile in ('N', 'n'): 
    print "Thank you!"
else:
    print "Didn't recognize user input"

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

You should do:

if viewYourFile == 'Y' or viewYourFile == 'y':

or as like @alecxe suggested, i.e.:

if viewYourFile in ('Y', 'y'):

Another good way that includes less typing is:

if viewYourFile.lower() == 'y':
Community
  • 1
  • 1
Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
  • Thanks Santosh. Voted up for that info. Wasn't aware that I would have to declare the variable twice using one parameter! – BubbleMonster Sep 05 '13 at 11:55
1

More smarter I think lead to one register:

if viewYourFile.lower() == 'y':
Denis
  • 7,127
  • 8
  • 37
  • 58