2010-02-11 15 views
12

Próbuję poprosić użytkownika o wprowadzenie numeru od 1 do 4. Mam kod, aby sprawdzić, czy numer jest poprawny, ale chcę, aby kod pętli kilka razy dopóki liczby nie będą poprawne. Czy ktoś wie, jak to zrobić? Kod jest poniżej:Uzyskaj instrukcję wypróbowania pętli, dopóki poprawna wartość nie zostanie uzyskana.

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() 

Ja również otrzymuję błąd o wyjątkiem Wszedłem:

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

dzięki za pomoc wyjątki

+9

To jest naprawdę zły projekt; nieprawidłowe wprowadzanie danych przez użytkownika nie jest w ogóle wyjątkiem. – unwind

Odpowiedz

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 - Dzięki za to. Ta praca jest najlepsza, wszystkie inne odpowiedzi są dobre, ale ten kod przechwytuje użytkownika wprowadzającego dowolną inną niepoprawną zmienną. – chrissygormley

5

Nowoczesne Python są zajęcia; przy użyciu raise 'incorrect' używasz przestarzałej funkcji języka o nazwie wyjątki napisów. Sekcja Errors and Exceptions samouczka w języku Python byłaby dobrym miejscem do rozpoczęcia podstawowej obsługi wyjątków w Pythonie.

Ogólnie rzecz biorąc, wyjątki nie są idealne dla twojej sytuacji - prosta pętla while powinna wystarczyć. Wyjątki powinny być zarezerwowane dla wyjątkowych sytuacji, a zły wkład użytkownika nie jest wyjątkowy, należy się spodziewać.

Wersja pętla oparte o Release będzie wyglądać następująco:

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) 

PS: a jest złą nazwą zmiennej; powinieneś prawdopodobnie zmienić go na chosen_option lub coś w tym stylu.

4

Twoje podejście wydaje się być bardzo rozwlekły sposób coś osiągnąć dość prosty:

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

Jesteś zarówno rzucanie i łapanie wyjątek w tym samym prostym bloku kodu - nie jest to, co jest wyjątkiem obsługa to około. Możesz to zrobić lepiej, wyłamując się z pętli lub utrzymując warunek. Np .:

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!' 

EDIT: błąd Dodane sprawdzanie w int parsowania.

2

Zamiast stosowania wyjątków mógłby zrobić coś takiego:

... 
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() może generować wyjątek przy wprowadzaniu znaków ... –

+0

To prawda. Nie nadaje się jako taki – 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) 
Powiązane problemy