1

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.

3
  • 2
    You were close, but forgot to update x in your for loop: x = switch(x) Commented May 31, 2019 at 23:55
  • @RooThaDude, I added an answer to your question. Hopefully, any of the alternatives I am adding will help you. Commented Jun 1, 2019 at 0:23
  • Possible duplicate of Python: How to toggle between two values Commented Jun 1, 2019 at 0:24

6 Answers 6

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.