如何在Python中创建切换功能?

时间:2019-05-31 23:38:56

标签: python

我很难创建一个在每次运行该函数时都在字符串“ X”和“ O”之间切换的程序。

因此,例如,第一次运行switcher()时,它会显示“ x”,而下次运行时,它会显示“ o”,第三次它会显示“ x”,依此类推

我已经能够在没有函数的情况下实现此功能,而仅使用if else循环,但是我无法使用函数实现它

def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)

它输出:

value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x

为了实现这一点,我将其设置为:当x = 0时,它打印“ X”,当它为1时,它打印“ O”,然后重置为0。它保持为0,仅给我x

6 个答案:

答案 0 :(得分:3)

使用itertools中的循环

我认为一种好的方法是在itertools中使用函数cycle

from itertools import cycle

def switch():
    return cycle(["X", "O"])

i = 0
for output in switch():
    i += 1
    print(output)
    if i == 5:
        break

输出:

X
O
X
O
X

使用全局变量

您还可以使用全局变量来跟踪最后生成的值。但是,使用全局变量不是一个好主意。

last_value = None

def switch():
    global last_value
    if last_value in (None, "O"):
        last_value = "X"
        return "X"
    last_value = "O"
    return "O"

for _ in range(5):
    print(switch())

输出:

'X'
'O'
'X'
'O'
'X'

使用局部变量

您还可以传递一个参数,该参数指示最后返回的值。

def switch(last_value):
    if last_value in (None, "O"):
        return "X"
    return "O"

last_value = None
for _ in range(5):
    last_value = switch(last_value)
    print(last_value)

输出:

X
O
X
O
x

答案 1 :(得分:1)

Clousers可能是最有趣,最简单的用例。概念可以在许多其他编程语言中使用,包括javascriptperl等,甚至语法也几乎相同:

def switch():
    string = 'o'
    def change():
        nonlocal string
        if(string == 'x'):
            string = 'o'
        else:
            string = 'x'
        return string

    return change

switcher = switch()
print(switcher())
print(switcher())
print(switcher())
print(switcher())

输出:

x
o
x
o

答案 2 :(得分:0)

这就是您要寻找的东西

class switcher:
    def __init__(self):
        self.cnt = -1

    def switch(self):
        self.cnt += 1
        return '0' if self.cnt % 2 else '1'


mySwitch = switcher().switch

print(mySwitch())
print(mySwitch())
print(mySwitch())
print(mySwitch())

这将打印:

1
0
1
0

还有其他方法可以实现此目的,例如使用装饰器。

答案 3 :(得分:0)

您可以使用布尔索引:

def switch(options=('X', 'O')):
    val = False
    while True:
        val = not val
        yield options[val]

switcher = switch()
for _ in range(5):
    print(next(switcher))

此打印:

O
X
O
X
O

答案 4 :(得分:0)

您可以执行以下操作……效果很好:

def switch(count):
    x = 0
    z = 1
    y = 0
    value = 1
    while x < count:
        if value == z:
            print(y)
            value = 0
        elif value == y:
            print(z)
            value = 1
        x+=1

然后:(基于计数,它会打印出许多更改)

switch(10)
0
1
0
1
0
1
0
1
0
1

答案 5 :(得分:0)

您可以为函数定义一个布尔属性,每次调用该函数时都将其切换:

def switch(value):
    if switch.state:
        print ('x')
    else:
        print('o')
    switch.state = not switch.state

switch.state = False
for x in range(4):
    switch(x)