我有一点Caesar Cipher代码,不能尝试/除了工作。它只是重复第一个输入。它不显示“INCORRECT INPUT”。我该怎么做才能解决这个问题?
while True:
try:
encrypt = raw_input("Would you like to encrypt or decrypt a message? (E/D) : ").lower()
print("")
if encrypt == 'e':
print("ENCRYPTION: Due to the nature of the Caesar Cipher, Numbers and Symbols will
be removed. Please represent numbers as the word...")
print("I.E. - 7 should be entered as 'seven'. ")
print("")
sentence = raw_input("Please enter a sentence : ").lower()
newString = ''
validLetters = "abcdefghijklmnopqrstuvwxyz "
space = []
for char in sentence:
if char in validLetters or char in space:
newString += char
shift = input("Please enter your shift : ")
resulta = []
for ch in newString:
x = ord(ch)
x = x+shift
resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != ' ' else ch)
print sentence
print("")
print("Your encryption is :")
print("")
print ''.join(resulta)
if encrypt == 'd':
print("DECRYPTION : PUNCTUATION WILL NOT BE DECRYPTED")
print("")
sentence = raw_input("Please enter an encrypted message : ").lower()
newString = ''
validLetters = "abcdefghijklmnopqrstuvwxyz "
for char in sentence:
if char in validLetters:
newString += char
shift = input("Please enter your shift : ")
decryptshift = 26 - shift
resulta = []
for ch in newString:
x = ord(ch)
x = x + decryptshift
resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != ' ' else ch)
print sentence
print("")
print("Your encryption is :")
print("")
print ''.join(resulta)
if encrypt == 'q':
break
except:
print("")
print("INCORRECT INPUT!")
print("")
continue
我尝试过各种各样的地方,除了......我迷路了。提前谢谢!
答案 0 :(得分:0)
我已经运行了你的代码,看起来没问题,在我修复了不匹配的标识之后:
if char in validLetters:
newString += char
到此:
if char in validLetters:
newString += char
我得到了以下输出:
Please enter a sentence : test
Please enter your shift :
INCORRECT INPUT!
答案 1 :(得分:0)
try..except
块。如果except
块成功完成,则不会执行try
块。在你的情况下,你的程序根本不会进入if
块。
要获得预期结果,请按如下所示重写if语句:
if encrypt == 'e':
...
elif encrypt == 'd':
...
elif encrypt == 'q':
break
else:
print("")
print("INCORRECT INPUT!")
print("")
这样,您可以组合所有条件,并具有“默认”语句。如果没有输入之前的else
和第一个elif
,那么elif
之后的if
将会输入(这基本上是说没有条件为真)。
如果您不使用elif
并且仅使用if
(与原始代码中一样),则条件链将被破坏,最后的else
将捕获所有案例其中encrypt != "q"
,即使是“e”或“d”。
答案 2 :(得分:0)
这是来自原始问题的IT,但是
result = raw_input("Enter Q, D, or E")
while result.lower() not in ["q","d","e"]:
result = raw_input("Invalid Response! Enter Q,D, or E:")
#now you know result is one of q d or e
可能是获取输入的更好方法