2013-03-07 52 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: ')