2013-06-04 4 views
0

는 최근에 나는 경우 else 문에 작은 문제가 생겼어요. 즉 나는 그가 해당 스크립트를 작성하거나하지 않은 파일을 읽을 수 원하는지 입력을 사용자에게 요청하는 함수를 만들려면, 그래서 입력되면 입력 내가 다시 질문을 되돌리려 잘못된 경우 올바른 기능을하지만 그 일을한다.출력에 따라 Python에서 함수를 반복하는 방법은 무엇입니까?

여기에 코드입니다 :

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) 

내가 할 수있는 기능을하고 싶은 것입니다 대신

else: 
    print "wrong input" 

돌아가서 자신을 반복하는 것입니다 물품.

+0

당신이 구글을 시도 했습니까? – kirelagin

+1

http://stackoverflow.com/questions/10563920/go-back-to-start-or-repeat-raw-input-a-number-of-times http://stackoverflow.com/questions/1781445/how- -l-raw-input-repeat-until-i-wanna-quit http://stackoverflow.com/questions/12557376/python-repeat-program-while-true – kirelagin

답변

0

방법에 대한이

 
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]) 
0

당신은이 while 루프를 사용하여 실현할 수 있습니다. break 나 sys.exit이 없을 때마다 시작으로 돌아갑니다. 이것은 잘못된 입력을 의미합니다. 이

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) 

희망이 도움 그러나 나는 코드를 조금 변경하는 것이 좋습니다. 이제 파일이 읽힐 때마다 읽는 지 여부를 결정합니다. 사용자가 '예'라고 말한 후에이 작업을 수행 할 수 있습니다. 당신이 with 문을 사용하는 경우 그리고, 파일은 다음 indended 부분에 opend됩니다. 여기서 파일을 읽습니다.

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" 
+0

고맙습니다. 이 작업을 수행하는 동안 while 문을 사용하면 with 문이 파일을 읽는 데 훨씬 합리적인 방법처럼 보입니다. 고맙습니다. –

0

이 시도 함수 본체를 while 루프로 랩핑하지 않아도됩니다.

은 당신이 재귀 return 직후 있는지 확인도 라인
else: 
    print "wrong input. Try again..." 
    read_the_file(output_file); 
    return; 

하여 라인

else: 
    print "wrong input" 

를 교체합니다.

파일이 존재하고 덮어 쓸 수 없습니다하는 경우는 새 이름을 묻는 다음 파일 이름에 기록 할 사용자를 묻는 때 나는이 트릭 편리한 발견했다.

0

또 다른 방법은 같은 기능으로 재귀 단지 - 그것은 "다시 시도"할 수있는 방법, 그리고 그것을 :

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) 
관련 문제