我的代码输出应该是这样的:
加密器:
Enter 1 to encipher or 2 to decipher: 1
Enter text you wish to encipher: My dog has fleas.
Enter the number of characters to shift: 7
The encrypted text is: Fr whz atl yextl.
破译:
Enter 1 to encipher or 2 to decipher: 2
Enter text you wish to decipher: Fr whz atl yextl.
The most likely shift is: 7
My dog has fleas.
到目前为止,我有这个并且我一直得到无效的语法。我对如何在输出中输入答案感到困惑。它应该是try / except with while循环,因为它是一个学校作业。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
if (num == 1):
num = int(raw_input('Enter a number:'))
num = int(raw_input('encipher'))
print "Enter text to encipher"
print "Enter the number of characters you want to shift"
elif (num == 2):
num = int(raw_input('Enter a number:'))
num = int(raw_input('decipher'))
print "Enter text to decipher"
print "Enter the number of characters you want to shift"
答案 0 :(得分:1)
你不一定非常需要使用try / except,但是如果你想尝试将转换转换为整数然后就可以了。主要问题是你在任何地方都没有一个except块。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
except ValueError as e:
print "You didn't enter a number. Try again"
答案 1 :(得分:1)
您没有正确使用try-except
。
想法是尝试一大堆代码;但如果遇到错误/异常,请做其他事情。
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
在你的脚本中,你试图接受一个数组中的int,并且你正在处理一个不在预定义选项列表中的场景。但是,如果它们是该代码块的例外,那么您没有做任何事情。
要使用try-except
,请执行以下操作:
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
if num in [1,2]:
break
print "You have to enter 1 or 2, try again"
except Exception, e:
print e