17个常见的Python运行时错误,你中招了没?
共 4364字,需浏览 9分钟
·
2021-12-30 03:28
作者:彭博 www.oschina.net/question/89964_62779
↑ 关注 + 星标 ,每天学Python新技能
后台回复【大礼包】送你Python自学大礼包
大家好,我是龙哥!
对于刚入门的Pythoner在学习过程中运行代码是或多或少会遇到一些错误,刚开始可能看起来比较费劲。随着代码量的积累,熟能生巧当遇到一些运行时错误时能够很快的定位问题原题。下面整理了常见的17个错误,希望能够帮助到大家。
if spam == 42
print('Hello!')
2、
if spam = 42:
print('Hello!')
3、
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
print('Howdy!')
在 for 循环语句中忘记调用 len()
导致“TypeError: 'list' object cannot be interpreted as an integer”
通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。
该错误发生在如下代码中:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
而正确做法是:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
numEggs = 12
print('I have ' + numEggs + ' eggs.')
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
numEggs = 12
print('I have %s eggs.' % (numEggs))
print(Hello!')
print('Hello!)
myName = 'Al'
print('My name is ' + myName + . How are you?')
8、
foobar = 'Al'
print('My name is ' + fooba)
spam = ruond(4.2)
spam = Round(4.2)
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10、
spam = ['cat', 'dog', 'mouse']
print(spam[6])
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
class = 'algebra'
Python3的关键字有:and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
13、
在一个定义新变量中使用增值操作符
导致“NameError: name 'foobar' is not defined”
不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。
该错误发生在如下代码中:
spam = 0
spam += 42
eggs += 42
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
spam = range(10)
spam[4] = -1
正确写法:
spam = list(range(10))
spam[4] = -1
(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)
spam = 1
spam++
spam = 1
spam += 1
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
推荐阅读