2013-03-07 55 views
0

我需要幫助這個數據驗證問題在Python 2.7中,它做我希望它不接受字符串,但它不接受整數,因爲它應該這樣做。Python 2.7的數據驗證

def GetKeyForCaesarCipher(): 
    while True: 
    key =(raw_input('Enter the amount that shifts the plaintext alphabet to the ciphertext alphabet: ')) 
    try: 
     i=int(key) 
     break 
    except ValueError: 
     print ('Error, please enter an integer') 

    return key 
+2

「你的意思是什麼都行不通」在這裏是一個有建設性的問題。我們需要知道代碼應該做什麼,以及它實際正在做什麼來正確診斷您的問題。下面,Martijn假設你想從函數中返回整數,但是這篇文章沒有辦法知道這個(合理的)假設是否正確。 – mgilson 2013-03-07 15:46:34

回答

5

它接受整數就好了,但是你返回的是原始字符串值。你要麼返回i或指定key代替:

key = int(key) 
+0

你先生是上帝,非常感謝你 – user1655562 2013-03-07 15:45:24

+0

嘿,你如何得到4 upvotes當我只有2 [這裏](http://stackoverflow.com/a/15275111/748858)。忍者技能? – mgilson 2013-03-07 15:47:41

+0

@mgilson幾乎現在。 – vikki 2013-03-07 15:50:55

0

的Martijn的答案是正確的,當然,但如果你的改進作風,你可能會發現更容易調試。試試看這樣:

def promptForInteger(prompt): 
    while True: 
    try: 
     return int(raw_input(prompt)) 
    except ValueError: 
     print ('Error, please enter an integer') 

def getKeyForCaesarCipher(): 
    return promptForInteger('Enter the amount that shifts the plaintext alphabet to the ciphertext alphabet: ')