问题描述
我在 python 中有一个函数可以对字符串进行错误检查.如果函数发现错误,它将返回一个带有错误代码和该错误标识符的元组.稍后在程序中我有处理错误的函数.它将元组接受为两个变量.
I have a function in python that does error checking on a string. If the function finds an error it will return a tuple with an error code and an identifier for that error. Later in the program I have the function that handles the error. It accepts the tuple into two variables.
errCode, i = check_string(s,pathType)
check_string 是产生元组的函数.如果没有错误,我希望它做的是返回零.当返回零时,上面的代码似乎失败了,因为变量 i 没有任何内容.
check_string is the function that produces the tuple. What I want it to does is return just zero if there is no error. When a zero is returned the above code seems to fail because there is nothing for the variable i.
是否有一种简单的方法可以让它工作,或者如果没有发现错误,我是否只需要让程序返回一个 0 和 0 的元组?
Is there an easy way to get this to work or do I just need to have the program return a tuple of 0 and 0 if no error is found?
推荐答案
我会为此使用异常系统.
I would use the exception system for this.
class StringError(Exception):
NO_E = 0
HAS_Z = 1
def string_checker(string):
if 'e' not in string:
raise StringError('e not found in string', StringError.NO_E)
if 'z' in string:
raise StringError('z not allowed in string', StringError.HAS_Z)
return string.upper()
s = 'testing'
try:
ret = string_checker(s)
print 'String was okay:', ret
except StringError as e:
print 'String not okay with an error code of', e.args[1]
这篇关于缺失值的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!