gpt4 book ai didi

python - 尝试/异常(exception)错误Python?

转载 作者:行者123 更新时间:2023-12-01 04:21:33 26 4
gpt4 key购买 nike

我的代码的输出应该如下所示:

加密:

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.

到目前为止,我已经得到了这个,但我不断收到无效的语法。我对如何在输出中输入答案感到困惑。它应该是带有 while 循环的 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"

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"

最佳答案

您没有正确使用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,并且您正在处理它不在预定义选项列表中的情况。但是,如果它们是该代码块的异常(exception),那么您就不会执行任何操作。

要利用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

关于python - 尝试/异常(exception)错误Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com