Python入门编程中常见的八种报错

    对于初学者而言,由于语法的不熟练等种种原因,会出现各种错误导致程序报错,本文选取八种常见的错误进行举例说明,希望可以帮助初学者进行错误纠正。

1. SyntaxError: 'return' outside function

for x in range(10):
    x += 1
    print(x)
    if x == 5:
        return
    else:
        pass
SyntaxError: 'return' outside function

Process finished with exit code 1

    这句报错提示意思是说,语法错误: 'return' 在方法外。不同于其他语言,在Python中,return只能用在方法中,如果用在别的地方,比如图中所示的独立的for循环中,就会出现这句报错信息。作为初学者,只要注意return的使用条件即可规避这个错误。

2. TypeError: must be str, not int

age = 18
name = input('')
print('我的名字是' + name + ',我的年龄是' + age)
TypeError: must be str, not int

Process finished with exit code 1

    这句报错提示意思是说,类型错误:必须是字符串类型,不能是整型。全局变量age的值是18,是一个整型,而程序打印时使用+进行字符串拼接时,错误的把age直接写了进去。在Python中‘’+‘’只能拼接字符串,因此在拼接之前应该先将age的类型转化为字符串即可正常使用。  

3. SyntaxError: invalid syntax

sex = True
if sex = False:
    print('她是女的')
else:
    print('他是男的')
SyntaxError: invalid syntax

Process finished with exit code 1

    这句报错提示意思是说,语法错误:非法语法。仔细看上述代码,if判断条件为 age = False,在Python语法中,若要比较两者是否相等,应用==,这是常见的语法错误。初学者可以通过看提示的的错误处在哪一行,从该行往上找语法错误,注意看细节处即可。

4. TypeError:pop expected at least 1 arguments,got 0

list1.pop()

    这句报错是说,类型错误:pop方法期望得到至少一个参数,但是现在参数为0。

5. IndexError:list index out of range

list1 = [1,2,3,4]
print(list[5])

     这句报错是说,索引错误:列表索引超出范围。解决方法:查看列表的长度,索引要小于长度

6. IndentationError:unindent does not match any outer indentation leve

if '张三'in list1:
           print('存在')
else:
    print('不存在')

    这句报错是说,缩进错误:未知缩进不匹配任何缩进等级。解决方法:使用Tab键进行缩进。

7. IndentationError: expected an indented block

if '张三'in list1:
     print('存在')
else:
print('不存在')

    这句报错是说,缩进错误:期望一个缩进TAB。解决方法:使用Tab键进行缩进。

8. KeyError: 'fond'

dic1 = {
    'name':'张三',
    'age': 17,
    'friend':['李四','王五','赵六','陈七']
}
print(dic1['fond'])

     这句报错是说,键错误:没有指定的键值。解决方法:补充对应的键值对或者修改查找的键值。

9. ValueError: substring not found

content = 'hello world'
result = content.index('2')
print(result)
      这句报错是说, 值错误:子字符串未找到。解决方法:补充或者修改对应的子字符串。

10. AttributeError: 'tuple' object has no attribute 'remove'

tp1 = ({},[],(),1,2,3,'a','b',True)
tp1.remove()
print(tp1)
     这句报错是说, 属性错误:元组对象没有属性remove。解决方法:对象打点查看具体属性。



猜你喜欢

转载自blog.csdn.net/qq_35866413/article/details/80992365