Python学习中遇到遇到的错误

学习的最有效途径是多试,记录几个问题:

1,for循环体中企图改变序列

正常是这样的:

>>>words = ['cat', 'window', 'defenestrate']

>>>forwinwords[:]:# words[:]是words的整体拷贝

iflen(w) > 6:

words.insert(0, w)

>>>words

['defenestrate', 'cat', 'window', 'defenestrate']

错误:

>>>words = ['cat', 'window', 'defenestrate']

>>>forwinwords:

iflen(w) > 6:

words.insert(0, w)#改变了words

然后解释器进入一个死循环了

此时按回车键并不会结束程序,且不出现“>>>”

按Restart shell才能强制结束解释器。

为了看到运行过程,修改程序:

>>>words = ['cat', 'window', 'defenestrate']

>>>forwinwords:

iflen(w) > 6:

words.insert(0, w)#改变了words

print(words)#加了这个语句

运行结果:不停打印

['defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'cat', 'window', 'defenestrate']

['defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'cat', 'window', 'defenestrate']

.....

列表长度不定,按Restart shell 才能强制结束解释器。

2,交互式解释器遇到的格式问题

出现缩进语法错误

正确格式:

>>>ifx < 0:

x=0

print('Negative changed to zero')

elifx == 0:

print('Zero')

elifx == 1:

print('Single')

else:

print('More')

More

这种情况不会在正常编辑器出现。只会在交互式解释器中出现。

3,生成器表达式

举例:

>>>words = ['cat', 'window', 'defenestrate']

>>>q=(wforwinwords)

>>>print(q)

>>>(wforwinwords)

>>>next(q)

'cat'

>>>next(q)

'window'

>>>next(q)

'defenestrate'

>>>next(q)

Traceback (most recent call last):

File "

", line 1, in

next(q)

StopIteration

>>> next((wforwinwords))

'cat'

>>> next((wforwinwords))

'cat'

>>> next((wforwinwords))

'cat'

>>> next((wforwinwords))

'cat'

每次的结果都是'cat',是因为(wforwinwords)表达式每次都重新返回一个生成器。

准确理解—与曾工一块学习

  • 发表于:
  • 原文链接:http://kuaibao.qq.com/s/20180117G0TT4R00?refer=cp_1026

扫码关注云+社区