pyton设计一个函数,让返回值的调用来回切换,调用一次,返回1,下次调用返回0
Consider a procedure make_toggle that might be used to create an on/off switch. If the switch is off (0), invoking it causes the switch to come on and return 1. Similarly, if the switch is on, invoking it again causes the switch to go off and return 0. >>> x = make_toggle(0)
>>> x()
1
>>> x()
0
>>> x()
1
Define and implement a make_toggle procedure that allows its initial state to be set. Use as few lines of code as possible.
以下是代码实现
#coding:utf-8
"""
由python培训_python爬虫等视频讲师所写.
视频下载地址
http://pan.baidu.com/share/link?shareid=641164583&uk=2620128624
"""
from itertools import cycle
def make_toggle(num):
"""利用迭代器和闭包实现,如果不需要设置初始状态,就更简单。
直接myIterator = cycle([1,0])
"""
if num == 0:
myIterator = cycle(range(2)[::-1])
def inner():
return myIterator.next()
return inner
else :
def inner():
return "please input num = 0"
return inner
x = make_toggle(0)
print x()
print x()
print x()
print x()
Consider a procedure make_toggle that might be used to create an on/off switch. If the switch is off (0), invoking it causes the switch to come on and return 1. Similarly, if the switch is on, invoking it again causes the switch to go off and return 0. >>> x = make_toggle(0)
>>> x()
1
>>> x()
0
>>> x()
1
Define and implement a make_toggle procedure that allows its initial state to be set. Use as few lines of code as possible.
以下是代码实现
#coding:utf-8
"""
由python培训_python爬虫等视频讲师所写.
视频下载地址
http://pan.baidu.com/share/link?shareid=641164583&uk=2620128624
"""
from itertools import cycle
def make_toggle(num):
"""利用迭代器和闭包实现,如果不需要设置初始状态,就更简单。
直接myIterator = cycle([1,0])
"""
if num == 0:
myIterator = cycle(range(2)[::-1])
def inner():
return myIterator.next()
return inner
else :
def inner():
return "please input num = 0"
return inner
x = make_toggle(0)
print x()
print x()
print x()
print x()