Python 为什么错误处理不适用于无输入? def副本列表(t): 尝试: 如果类型(t)为列表: t_copy=[] n=长度(t) i=0 而我

Python 为什么错误处理不适用于无输入? def副本列表(t): 尝试: 如果类型(t)为列表: t_copy=[] n=长度(t) i=0 而我,python,Python,您的代码不会引发异常,因为您使用检查t的类型是否为列表,如果类型(t)为列表。当您提供None作为输入时,它不会通过if语句,因此不会返回任何内容,也不会引发异常 您可以删除if语句来引发异常n=len(t)将触发异常,因为您无法获取None的长度(TypeError:type'NoneType'的对象没有len() ),将返回“非列表” def copy_list(t): try: if type(t) is list: t_copy=[] n=len(

您的代码不会引发异常,因为您使用
检查
t
的类型是否为列表,如果类型(t)为列表
。当您提供
None
作为输入时,它不会通过
if
语句,因此不会返回任何内容,也不会引发异常

您可以删除
if
语句来引发异常
n=len(t)
将触发异常,因为您无法获取
None
的长度(
TypeError:type'NoneType'的对象没有len()
)
,将返回
“非列表”

def copy_list(t):
try:
    if type(t) is list:
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
except TypeError:
        return "Not a list"
试试看:
t_copy=[]
n=长度(t)
i=0

当我把它扔进一个
for
循环时,
if-type
应该会捕获其他内容

try:
    t_copy=[]
    n=len(t)
    i=0
    while i<n:
        t_copy.append(t[i])
        i+=1
    return t_copy
except TypeError:
    return "Not a list"
或者更简洁地说:

def copy_list(t):
    if type(t) is list:
        t_copy=[]
        for i in t:
            t_copy.append(i)
        return t_copy
    else:
        return "Not a list"
y = None
x = copy_list(y)
print x
y = "abc"
x = copy_list(y)
print x
y = [1,2,3,4,5,6,7,8,9]
x = copy_list(y)
print x
结果为:

def copy_list(t):
    if type(t) is list:
        t_copy = list(t)
        return t_copy
    else:
        return "Not a list"
y = ""
x = copy_list(y)
print x,"\t", type(y)
y = []
x = copy_list(y)
print x,"\t\t", type(y)
y = None
x = copy_list(y)
print x,"   ", type(y)
y = 10
x = copy_list(y)
print x,"   ", type(y)
y = "abc"
x = copy_list(y)
print x,"   ", type(y)
y = [1,2,3,4]
x = copy_list(y)
print x,"   ", type(y)
y = ["a",2,"b"]
x = copy_list(y)
print x,"   ", type(y)
y = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
x = copy_list(y)
print x,"   ", type(y)     
不是列表
[]      
不是名单
不是名单
不是名单
[1, 2, 3, 4]    
[a',2',b']
不是名单

try/except块用于在遇到意外或非法值时优雅地处理解释器引发的异常,而不是故意引发异常。为此,您需要
raise
关键字。见这个问题:

作为建议,您的代码可以如下所示:

Not a list  <type 'str'>
[]      <type 'list'>
Not a list  <type 'NoneType'>
Not a list  <type 'int'>
Not a list  <type 'str'>
[1, 2, 3, 4]    <type 'list'>
['a', 2, 'b']   <type 'list'>
Not a list  <type 'dict'>
def副本列表(t):
如果存在(t,列表):
t_copy=[]
n=长度(t)
i=0

当我使用你的
if
语句只在
t
作为一个列表时触发时,其他语句都不会尝试在非列表上运行,因此你从未遇到任何会引起豁免的代码。那么我如何修改我的代码以达到except语句呢?你正在捕获
TypeError
;您希望在
try
块中的哪一行引发该异常?(此外,由于捕获异常,因此违反了函数应抛出异常的规定。由于函数应抛出异常,因此不应在此处捕获错误。)这不是
try..except
的好用法。只要
if..else
就足够了。也许他们想让你使用
断言类型(t)is list
。当通过一个非列表、非None值时,此代码可能仍然无法通过测试。它仍然无法通过None输入这不会使None测试失败,虽然如果通过考试就会失败,但仍然没有一个考试不及格input@Varun我强烈反对这一评论。看看打印的结果。不客气!当他们为你工作时,考虑接受答案,欢迎来到网站!为了公平起见,在评论了其他答案后,该答案以优异成绩通过了测试。
def copy_list(t):
    if isinstance(t, list):
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
    else:
        raise Exception('Not a list')