Python,为什么在使用generator yield时,在.py和shell之间得到不同的结果?

Python,为什么在使用generator yield时,在.py和shell之间得到不同的结果?,python,generator,Python,Generator,我正在学习协同程序,我发现了一个名为“关于协同程序和Concurrecy的有趣课程”的pdf文件。 有一个很奇怪的例子: def countdown(n): print("Counting down from", n) while n >= 0: newvalue = (yield n) # If a new value got sent in, reset n with it if newvalue is not None: n = newvalu

我正在学习协同程序,我发现了一个名为“关于协同程序和Concurrecy的有趣课程”的pdf文件。 有一个很奇怪的例子:

def countdown(n):
print("Counting down from", n)
while n >= 0:
    newvalue = (yield n)
    # If a new value got sent in, reset n with it
    if newvalue is not None:
        n = newvalue
    else:
        n -= 1
我把它放在一个名为“bogus.py”的文件中,然后我转到python shell

>>> from bogus import countdown
>>> c = countdown(5)
>>> for n in c:
...     print(n)
...     if n == 5:
...         c.send(3)
...
Counting down from 5
5
3
2
1
0
>>>
是的,我有532110。。。 但是当我把这些语句放到bogus.py中时,我得到了不同的结果

def countdown(n):
print("Counting down from", n)
while n >= 0:
    newvalue = (yield n)
    # If a new value got sent in, reset n with it
    if newvalue is not None:
        n = newvalue
    else:
        n -= 1

c = countdown(5)
for n in c:
    print(n)
    if n == 5:
        c.send(3)
然后

$ python bogus.py
Counting down from 5
5
2
1
0
我得了5210。。。!3号线在哪里? 我很困惑,我真的不知道为什么。。。 请帮帮我,对不起我的英语

哦,我还发现如果我对shell代码做了一点修改,那么我得到:

>>> from bogus import countdown
>>> c = countdown(5)
>>> for n in c:
...     print(n)
...     if n == 5:
...         k = c.send(3)
...
Counting down from 5
5
2
1
0
>>>

在交互模式下,Python自动打印计算结果不是
None
的任何表达式语句的
repr
。这不包括函数和类中的表达式语句,但包括循环中的表达式语句,例如:

>>> for n in c:
...     print(n)
...     if n == 5:
...         c.send(3)  # <- right here
>对于c中的n:
...     打印(n)
...     如果n==5:
...         c、 发送(3)#