def mainloop():
inp = input("Which cipher would you like to use?\n[A]a1z26\n[B]Atbash\n[C]Caesar\n[D]ROT13\n>")
elif inp.lower() == 'c':
inp = input("Would you like to decipher or encipher a text?\n>")
while inp.lower() not in ('decipher', 'encipher'):
inp = input("Please enter either 'decipher' or 'encipher'.\n>")
if inp.lower() == 'decipher':
inp1 = input("What text would you like to decipher?\n>")
while True:
try:
inp2 = int(inp2)
except ValueError:
inp2 = int(input("Please enter a valid number.\n>"))
dec_caesar(inp1, inp2)
So the code by itself works and edge cases have already been implemented in my code but I made it shorter so it is easier to read. Essentially what I want is to have inp2
be a number of shift for the cipher, eg if inp2 == 1
and the letter is a it would shift by 1 to become b
, and I've already coded this. The problem is handling the case when inp2
cannot be an integer. By default an input is a string
so I use int(input)
and the except ValueError
works the first time, but if i type a string
again, it will just Raise a ValueError
instead of running the except ValueError
. How can I make it so it would keep asking to enter a valid number until int(input)
is valid?
the above code produces the error:
Traceback (most recent call last):
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 97, in mainloop
inp2 = int(inp2)
ValueError: invalid literal for int() with base 10: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 105, in <module>
mainloop()
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 99, in mainloop
inp2 = int(input("Please enter a valid number.\n>"))
ValueError: invalid literal for int() with base 10: 'a'