输入不是字符串或长度不确定时的Python函数错误

输入不是字符串或长度不确定时的Python函数错误,python,function,error-handling,Python,Function,Error Handling,我是Python新手,对于如何设计一个函数来显示输入不是长度为21的字符串时的错误消息,我对文献感到困惑。这是不起作用的最新排列。例如,对于长度为19的字符串,它不会返回正确的错误消息。我的背景不是comp-sci,所以任何关于这方面的帮助和解释都会很有帮助。谢谢 test = "test_string_for_slice" test2 = "test_string_for_" def stringSlice(x): if type(x) != str: raise E

我是Python新手,对于如何设计一个函数来显示输入不是长度为21的字符串时的错误消息,我对文献感到困惑。这是不起作用的最新排列。例如,对于长度为19的字符串,它不会返回正确的错误消息。我的背景不是comp-sci,所以任何关于这方面的帮助和解释都会很有帮助。谢谢

test = "test_string_for_slice"
test2 = "test_string_for_"

def stringSlice(x):
    if type(x) != str:
        raise Exception("The input is not a string.")
    elif len(x) != 21:
        raise ValueError("The input is not exactly 21 characters.")
    else:
        slice1 = x[0:6]
        slice2 = x[6:12]
        slice3 = x[13:]
        return slice1, slice2, slice3

stringSlice(test)
stringSlice(test2) #this should return an error but does not

当您打算使用
x
时,似乎正在使用变量
occCode

def stringSlice(x):
    if type(x) != str:
        raise Exception("The input is not a string.")
    elif len(x) != 21:   #Note this is where things got changed!!!
        raise ValueError("The input is not exactly 21 characters.")
    else:
        slice1 = x[0:6]
        slice2 = x[6:12]
        slice3 = x[13:]
        return slice1, slice2, slice3

什么是
occCode
?将
occCode
更改为
x
,这是函数提供的参数。欢迎使用StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。是,将occCode更改为x。很抱歉,您的代码似乎正在正常工作?