2013-05-22 41 views
4

所以,我想在這裏做的是,如果你把一個字符串,而不是一個整數,你回去開始在Python 3(例外,循環)憋屈錯誤

但對於一些因此,當你把一個字符串

while True: 
    try: 
     print("Will select a random number between selected limits: 'x' and 'y'") 
     x = int(input("x = ")) 
    except ValueError: 
     print("Please enter a number") 
     break 

回答

5
while True: 
    try: 
     print("Will select a random number between selected limits: 'x' and 'y'") 
     x = int(input("x = ")) 
     y = int(input("y = ")) 
    except ValueError: 
     print("Please enter a number") # don't break here, let loop repeat 
    else: 
     break # only break when there is no error 
+0

你是正確的也有壓痕埃羅r –

+0

將'break'放在'else:'塊中,而不是放在'try:'塊的末尾是什麼意思? – chenaren

+1

@chenaren只是一個個人風格的問題,我認爲這樣感覺更順序 – jamylak

1

更短,通過一行程序只是停止):

while True: 
    try: 
     print("Will select a random number between selected limits: 'x' and 'y'") 
     x = int(input("x = ")) 
     y = int(input("y = ")) 
     break # only break when there is no error 
    except ValueError: 
     print("Please enter a number") # don't break here, let loop repeat