[英]Try/Except error Python?
The output of my code is supposed to look like: 我的代码输出应该看起来像:
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.
So far I have this and I keep getting invalid syntax. 到目前为止,我有这个,而且我一直在获取无效的语法。 I am confused on how to be able to type an answer in the output.
我对如何在输出中键入答案感到困惑。 It's supposed to be try/except with a while loop because it is a school assignment.
应该使用try / except并加上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"
You don't absolutely need to use a try/except, but if you want to try to do the conversion to integer right then and there, you could. 您不一定需要使用try / except,但是如果您想立即在该处进行到整数的转换,则可以。 The main problem is that you don't have an except block anywhere.
主要问题是您在任何地方都没有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"
You're not using a try-except
correctly. 您没有正确使用
try-except
。 The idea is to try a chunk of code; 这个想法是尝试代码的一部分。 but if it runs into an error/exception, do something else.
但是如果遇到错误/异常,请执行其他操作。
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"
In your script you are trying to take in an int that is in an array and you are handling a scenario in which it is not in your pre-defined list of options. 在脚本中,您尝试采用数组中的int,并且正在处理方案,该方案不在您的预定义选项列表中。 However, you are not doing anything if their is an exception to that chunk of code.
但是,如果它们是该代码块的例外,则您什么也不做。
To utilize the try-except
do the following: 要使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.