2010-02-11 3 views
12

사용자가 1에서 4 사이의 숫자를 입력하게하려고합니다. 숫자가 맞는지 확인하는 코드가 있지만 여러 번 반복 할 수 있도록 코드를 넣고 싶습니다. 숫자가 맞을 때까지 누구든지이 작업을 수행하는 방법을 알고 있습니까? 코드는 다음과 같습니다 :정확한 값이 얻어 질 때까지 루프를 반복하는 Try 문을 얻으십시오.

def Release(): 


    try: 
     print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n' 
     a = int(input("Please select the type of release required: ")) 
     if a == 0: 
      files(a) 
     elif a == 1: 
      files(a) 
     elif a == 2: 
      files(a) 
     elif a == 3: 
      files(a) 
     else: 
      raise 'incorrect' 
    except 'incorrect':  
     print 'Try Again' 
    except: 
     print 'Error' 

Release() 

나는 또한 내가 입력 한 예외에 대한 오류를 얻고있다 :

+9

이것은 정말 나쁜 디자인입니다; 잘못된 사용자 입력은 실제로 예외가 아닙니다. – unwind

답변

29
def files(a): 
    pass 

while True: 
    try: 
     i = int(input('Select: ')) 
     if i in range(4): 
      files(i) 
      break 
    except:  
     pass 

    print '\nIncorrect input, try again' 
+0

@ jellybean - 감사합니다. 이 작업은 최상이지만 다른 모든 대답은 좋지만이 코드는 사용자가 다른 잘못된 변수를 입력하는 경우를 포착합니다. – chrissygormley

5

현대 파이썬 예외 클래스입니다 어떤 도움

kill.py:20: DeprecationWarning: catching of string exceptions is deprecated 
    except 'incorrect': 
Error 

감사합니다; raise 'incorrect'을 사용하면 문자열 예외라는 더 이상 사용되지 않는 언어 기능을 사용하고 있습니다. 파이썬 자습서의 Errors and Exceptions 섹션은 파이썬에서 기본적인 예외 처리를 시작하는 데 좋은 장소입니다.

일반적으로 상황에 따라 예외적 인 경우는 많지 않으므로 간단한 루프 while이면 충분합니다. 예외는 예외적 인 상황을 위해 예약되어야하며 나쁜 사용자 입력은 예외는 아니며 예상됩니다.

def Release(): 
    a = None 
    while a not in (0, 1, 2, 3): 
     print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n' 
     try: 
      a = int(input("Please select the type of release required: ")) 
     except ValueError: 
      pass # Could happen in face of bad user input 
    files(a) 

추신 :

Release의 루프 기반 버전은 다음과 같을 것 a은 잘못된 변수 이름입니다. 아마도 chosen_option 또는 그와 비슷한 것으로 변경해야합니다.

4

귀하의 접근 방식은 매우 간단 뭔가 달성하기 매우 장황한 방법이 될 것 같다 : 당신은 던지기와 동일한 코드 단순 블록에서 예외를 잡는 모두

def Release() : 
    while True : 
     print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n' 
     a = int(input("Please select the type of release required: ")) 
     if 0 <= a < 4 : 
      files(a) 
      break 
     else : 
      print('Try Again') 
3

을 -이 어떤 예외 정말 아니다 취급은 대략이다. 루프를 벗어나거나 조건을 유지하여 더 잘 수행 할 수 있습니다. 예컨대 :

def isNumberCorrect(x): 
    return x in range(4) 

def Release(): 
    num = None # incorrect 

    while not isNumberCorrect(num): 
     print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n' 
     num_str = raw_input("Please select the type of release required: ") 

     try: 
      num = int(num_str) 
     except ValueError: 
      num = None 

     if not isNumberCorrect(num): 
      print 'Incorrect!' 

    # work with num here; it's guaranteed to be correct. 

if __name__ == '__main__': 
    try: 
    Release() 
    except: 
    print 'Error!' 

편집 : INT 구문 분석에서 확인 추가 오류가 발생했습니다. 대신 이런 식으로 뭔가 할 수있는 예외를 사용

2

:

... 
a = raw_input("Please select the type of release required:") 
while a not in ['0','1','2','3']: a = raw_input("Try again: ") 
files(int(a)) 
... 
+2

int()가 문자 입력시 예외를 throw 할 수 있습니다 ... –

+0

사실입니다. 그런대로 사용할 수 없습니다 – Anssi

1
def Release(): 
    while 1: 
     print """Please select one of the following? 
       Completion = 0 
       Release ID = 1 
       Version ID = 2 
       Build ID = 3 
       Exit = 4 """    
     try: 
      a = int(raw_input("Please select the type of release required: ")) 
     except Exception,e: 
      print e 
     else: 
      if a==4: return 0 
      files(a)