如何检查用户是否输入整数(Python)

时间:2017-09-08 19:05:35

标签: python caesar-cipher

我可能经常用Python询问我的项目(因为我已经有3个帮助请求了)但我只是希望能够做到最好。这次我想制作一个if语句来检查用户是否输入了一个整数(数字)而不是其他东西,因为当他们没有输入数字时,程序就会崩溃而我不喜欢,我喜欢用一条消息提示他们,他们需要输入一个数字,而不是别的。

这是我的代码:

def main():
    abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
    message = input("What's the message to encrypt/decrypt? ")
    key = int(input("What number would you like for your key value? "))
    choice = input("Choose: encrypt or decrypt. ")
    if choice == "encrypt":
        encrypt(abc, message, key)
    elif choice == "decrypt":
        encrypt(abc, message, key * (-1))
    else:
        print("Bad answer, try again.")

def encrypt(abc, message, key):
    text = ""
    for letter in message:
        if letter in abc:
            newPosition = (abc.find(letter) + key * 2) % 52
            text += abc[newPosition]
        else:
            text += letter
    print(text)
    return text

main()

我猜if语句需要在def encrypt(abc, message, key)方法的某处,但我可能错了,请你帮我找到解决方法,我非常感谢你的时间帮助我。

感谢!!!

1 个答案:

答案 0 :(得分:0)

使用try .. except

try:
    key = int(input('key : '))
    # => success
    # more code
except ValueError:
    print('Enter a number only')

在您的代码中:

def main():
    abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
    message = input("What's the message to encrypt/decrypt? ")
    choice = input("Choose: encrypt or decrypt. ")
    def readKey():
      try:
        return int(input("What number would you like for your key value? "))
      except ValueError:
        return readKey()
    key = readKey()
    if choice == "encrypt":
        encrypt(abc, message, key)
    elif choice == "decrypt":
        encrypt(abc, message, key * (-1))
    else:
        print("Bad answer, try again.")

def encrypt(abc, message, key):
    text = ""
    for letter in message:
        if letter in abc:
            newPosition = (abc.find(letter) + key * 2) % 52
            text += abc[newPosition]
        else:
            text += letter
    print(text)
    return text

main()