2010-02-11 16 views
12

Kullanıcı 1 ile 4 arasında bir sayı girmeye çalışıyorum. Sayının doğru olup olmadığını kontrol etmek için kodum var ancak kodun birkaç kez dönmesini istiyorum sayılar doğru olana kadar. Bunu yapmayı bilen var mı? kod aşağıda:Alınan doğru değer elde edilinceye kadar bir Deneme deyimi alın

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

Ben de girmiş istisna ilgili bir hata alıyorum:

+9

Bu gerçekten kötü bir tasarımdır; Burada yanlış kullanıcı girişi gerçekten bir istisna değildir. – unwind

cevap

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

olarak kullanılamaz Jellybean - Bunun için teşekkürler. Bu çalışma en iyisi, diğer tüm cevaplar iyi ama bu kod, kullanıcının başka bir yanlış değişkeni girmesini sağlıyor. – chrissygormley

5

Modern Python istisnalar sınıfları hiçbir yardım için

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

teşekkür; raise 'incorrect' kullanarak, dize istisnaları olarak adlandırılan kullanımdan kaldırılmış bir dil özelliği kullanıyorsunuz. Python öğreticisinin Errors and Exceptions bölümü, Python'da temel istisna işlemiyle başlamak için iyi bir yer olabilir.

Genel olarak, durumunuz için istisnalar genelde uygun değildir; basit bir while döngü yeterli olmalıdır. İstisnai durumlar için istisnalar ayrılmalı ve kötü kullanıcı girişi istisna değildir, beklenen bir durumdur.

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) 

Dip not:

Release ait döngü tabanlı sürümü bu gibi bir şey olur a, bozuk bir değişken addır; Muhtemelen chosen_option ya da bunun gibi bir şey değiştirmelisiniz.

4

Kişisel yaklaşım oldukça basit bir şey başarmak için çok uzun soluklu bir yol olarak görünüyor: Sen atma ve kod aynı basit bloğunda istisna alıcı hem

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

- bu nedir istisna gerçekten değil işleme hakkında. Bir döngüden çıkarak ya da bir koşulu muhafaza ederek daha iyisini yapabilirsiniz. Örn .:

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

DÜZENLEME: int ayrıştırma kontrol Eklendi hatası. Bunun yerine böyle bir şey yapabileceğini istisnaları kullanmanın

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() karakter girişi için bir istisna atabilir ... –

+0

Bu doğrudur. Böyle – 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)