Search code examples
pythoncaesar-cipher

How to check if user inputs an integer (Python)


I might be constantly asking about my project with Python (since I have 3 help requests already up) but I just want to make this the best it can be. This time I want to make an if statement to check if the user inputs an integer (number) instead of something else because when they don't type a number, the program will just crash and I don't like that, I like prompting them with a message saying that they need to type in a number and nothing else.

Here is my code:

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

I'm guessing the if statement needs to be somewhere in the def encrypt(abc, message, key) method but I could be wrong, could you please help me find out how to solve this, I would greatly appreciate your time to help me out.

THANKS!!!


Solution

  • Use try .. except:

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

    In your code:

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