0

Recently I've got a small problem with if else statement. Namely I want to create a function that asks user for input whether he wants to read the file that script has created or not, so if the input is correct function does its thing however when input is incorrect I want it to revert to question again.

Here's the code:

def read_the_file(output):
    print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
    """
    question = raw_input("> ")
    reading = output.read()
    if question == 'yes'or question == 'Y' or question == 'y':
        print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
    elif question == 'no' or question == 'N' or question == 'n':
        sys.exit[1]
    else :
        print "wrong input"

read_the_file(output_file)

so what I'd like the function to do is instead write

else:
    print "wrong input"

is to go back and repeat itself.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Konrad Wąsowicz
  • 422
  • 2
  • 6
  • 12
  • Have you tried Google? – kirelagin Jun 04 '13 at 07:59
  • 1
    http://stackoverflow.com/questions/10563920/go-back-to-start-or-repeat-raw-input-a-number-of-times http://stackoverflow.com/questions/1781445/how-to-let-a-raw-input-repeat-until-i-wanna-quit http://stackoverflow.com/questions/12557376/python-repeat-program-while-true – kirelagin Jun 04 '13 at 08:00

4 Answers4

0

You can realize this using a while loop. It returns to the start whenever there was no break or sys.exit, which means on every wrong input here. Hope this helps

def read_the_file(output):
        while True:
            print """
        Do you want me to read your newly created file?
        Type [Y]es or [N]o
            """
            question = raw_input("> ")
            reading = output.read()
            if question == 'yes'or question == 'Y' or question == 'y':
                print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
                break  # or sys.exit
            elif question == 'no' or question == 'N' or question == 'n':
                sys.exit[1]
            else :
                print "wrong input"

read_the_file(output_file)

But I would recommend to change the code a bit. Now everytime the file gets read, whether you want to read it or not. You could do this after the user said 'yes'. And if you use the with statement, the file will only be opend for the following indended part. Here the file gets read.

 def read_the_file(output):
        while True:
            print """
        Do you want me to read your newly created file?
        Type [Y]es or [N]o
            """
            question = raw_input("> ")

            if question == 'yes'or question == 'Y' or question == 'y':
                # Open and read file here
                with open(output, 'r') as f:
                    reading = f.read()
                    # File is now closed
                print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
                break  # or sys.exit
            elif question == 'no' or question == 'N' or question == 'n':
                sys.exit[1]
            else :
                print "wrong input"

read_the_file(output_file)
Exac
  • 113
  • 9
  • Thanks a lot, haven't realized i can use the while to accomplish this, also the with statement seems like a lot more reasonable way to read the file. Thank you. – Konrad Wąsowicz Jun 04 '13 at 08:27
0

try this:

def read_the_file(output):

    reading = open(output, "rb").read()
    while True:
        question = raw_input("Do you want me to read your newly created file?\
                        Type [Y]es or [N]o :")
        if question in ["Yes","yes","YES", "y","Y"]:

            print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
            break

        elif question in ["NO", "no", "n", "N"]:
            sys.exit[1]

        else:
            print "wrong input"
abhishekgarg
  • 1,480
  • 9
  • 14
0

How about this

import sys
def getUserResponse():
   print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
    """
   return raw_input("> ")

def read_the_file(output_file):
   output = open(output_file)

   question = getUserResponse()
   while (True):
      if question == 'yes' or question == 'Y' or question == 'y':
         reading = output.read()
         print "BEGINNING OF FILE\n\n" + reading + "\n END OF FILE"
      elif question == 'no' or question == 'N' or question == 'n':
         output.close()
         exit(1)
      else:
         print "wrong input"
      question = getUserResponse()
   output.close()

read_the_file(sys.argv[1])
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
0

Another way is just to recurse into the same function--it's a way to "try again", and it avoids having to wrap your function body into a while loop.

Replace your line

else:
    print "wrong input"

by the lines

else:
    print "wrong input. Try again..."
    read_the_file(output_file);
    return;

also, make sure that you return directly after recursing.

I have found this trick handy when asking a user for a filename to write to, and then asking for a new name if the file exists and should not be overwritten.

phfaist
  • 253
  • 4
  • 6
  • Recursion consumes stack; if you tried to do it endlessly, your program would eventually crash. (Some programming languages support tail call optimization, where having a function call at the very end of a function just replaces the current stack frame and so doesn't cause the stack to grow, but Python isn't one of those languages). – Charles Duffy May 01 '19 at 09:38