在Python中尝试/例外
我的代码应该输出:在Python中尝试/例外,python,try-catch,except,try-except,Python,Try Catch,Except,Try Except,我的代码应该输出: Encipher 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. Decipher Enter 1 to encipher or 2 to decipher: 2 Enter t
Encipher
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.
Decipher
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使我的代码实现这一点
while True:
try:
num = int(raw_input('Enter 1 or 2:'))
break
except ValueError:
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"
你眼前的问题是,你没有得到一个例外,因为输入的数字与你打印的文本不匹配。Python不会自动读取和解释发送到屏幕的消息。相反,在顶部尝试这么多:进入一个坚持合法数据的无限循环。继续,直到你得到合法的数据。抓取每个号码,检查是否合法;如果符合您的需要,请退出循环
while True:
while True:
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):
...
在继续之前,只编写几行代码并使其正常工作,这样做很好。请注意,在下面的代码中有一些概念上的问题。对于isntance,您要求用户输入要加密的文本,然后尝试将其转换为整数。那会让你犯错误
如果您再次陷入困境,请发布新问题。那么问题到底是什么?它的表现如何不像您期望的?欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布代码并准确描述问题之前,我们无法有效地帮助您。它不起作用,不是一个准确的描述。典型的反应是,这是因为它的编码错误-如果允许这行num=intraw_input'Enter 1或2:,则在用户输入任何整数(而不仅仅是1/2)时都会发生这种情况!然后中断线将运行,这意味着它将中断while循环。因为代码的其余部分在while循环中,所以代码的其余部分不会运行。取出break语句并在[1,2]中添加if num(如果num不在):raisevalueerrornow things。输入周围缺少一个try块。您应该在集合上使用in,而不是列表,因为这是一种更快的查找:为什么不消除嵌套的while,如果num==1,就这样做:。。。elif num==2:。。。否则:打印“重试”?内部循环获得合法输入;外部循环继续加密和解密,直到用户死亡并被放入一个密码中。对,但不需要嵌套循环。请注意,嵌套循环版本最终会检查num两次。