Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试/排除Python错误?_Python_Try Catch_Except_Try Except - Fatal编程技术网

尝试/排除Python错误?

尝试/排除Python错误?,python,try-catch,except,try-except,Python,Try Catch,Except,Try Except,我的代码的输出应该如下所示: 加密: 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

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

加密:

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加上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"

您不一定需要使用try/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"

您没有正确使用
之外的其他尝试。
想法是尝试一段代码;但如果遇到错误/异常,请执行其他操作

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,并且您正在处理一个场景,在该场景中,int不在预定义的选项列表中。但是,如果它们是该代码块的一个例外,那么您就什么也不做

要使用
请尝试执行以下操作:

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,缩进让我感到困惑。我认为您应该将其范围缩小到
,除了ValueError
。捕获所有异常可能会隐藏其他错误。