Roo Tha Dude
Roo Tha Dude

Reputation: 33

How to create a switching function in Python?

I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

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)

it outputs:

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

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

Upvotes: 1

Views: 612

Answers (6)

Sachin Dangol
Sachin Dangol

Reputation: 504

Probably most fun and simple use case of Clousers. Concept works in many other programming languages including javascript, perl etc and even syntax is almost same:

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

    return change

switcher = switch()
for _ in range(4):
    print(switcher())   

output:

x
o
x
o

Upvotes: 1

Masoud
Masoud

Reputation: 1280

You can define an Boolean attribute for the function, toggle it each time the function is called:

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)

Upvotes: 0

enjoyingthis
enjoyingthis

Reputation: 11

You could do something like this...works pretty well:

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

Then: (Based on the count it prints however many alterations)

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

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69903

Using cycle from itertools

I think a good approach is to use the function cycle in itertools

from itertools import cycle

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

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

Output:

X
O
X
O
X

Using a global variable

You can also use a global variable to keep track of the last generated value. However, it is not a good idea to use a global variable.

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())

Output:

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

Using a local variable

You can also pass a parameter that indicates the last value that was returned.

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)

Output:

X
O
X
O
x

Upvotes: 3

Jab
Jab

Reputation: 27515

You could use boolean indexing:

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

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

This prints:

O
X
O
X
O

Upvotes: 0

Perplexabot
Perplexabot

Reputation: 1989

Is this what you are looking for:

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())

This will print:

1
0
1
0

There are other methods to achieve this, like using decorators.

Upvotes: 0

Related Questions