我试图演示如何yield
在Python中使用。我想通过一个例子来证明这一点。
该示例将要求用户输入yes
或no
,并且n
每次yes
输入时将计数器加1 。
我要展示的yield
工作原理是用户再次调用该函数,并获得更新次数的值。例如,如果使用return,并且用户再次运行脚本,它将从头开始,并且次数为1
。相反,我希望用户获得1,2,3,...等,这是输入yes的次数。
这里的问题是如何yield
用来演示这样的例子。在下面的代码中,我总是得到一个generator object
返回值,而不是的值n
。如何获取n
返回的整数值?
def yes_times(answer):
n = 0
if answer == 'yes':
n = n + 1
yield n
answer = raw_input('"yes" or "no": ')
times = yes_times(answer)
print 'You answered yes ' + str(times) + ' times'
谢谢。
例如,您可以尝试:
def yes_times(answer = None):
count = 0
while True:
if answer=="yes":
count += 1
answer = yield count
else:
answer = yield count
gen = yes_times()
gen.next()
while True:
answer = raw_input('"yes" or "no": ')
print 'You answered yes ' + str(gen.send(answer)) + ' times'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句