0

Just stuck in my code, was looking for others source, but there's other implementation, I must be blind or ... but it looks like functions are referring still to one variable, when in my beginning understanding if I call function which return 'change', and function return back to a place in code when it should not reach declared earlier variable, but that variable returned from function and next calling same function should again switch my variable (X and O), just cut a piece of this code: got X or O (what I'm choosing), printing variable correct, but then function output is X X X and so on... (I'm just started to learn, but just stuck here!)

def choice():
    choice = input("You want to have x or o?: ")
    if choice == 'x':
        human = 'X'
        computer = 'O'
    else: 
        human = 'O'
        computer = 'X'
    return human, computer

human, computer = choice()
print("human is ", human)
print("computer is ", computer)

def next_player(turn):
    if turn == 'X':
        return 'O'
    else:
        return 'X'

turn = 'X'

print("turn is ", turn)
turn = next_player(turn) # was here: next_player(turn) and so below!!
print("after next player function turn is ", turn)
turn = next_player(turn)
print("after next player function turn is ", turn)
Mikko
  • 1,877
  • 1
  • 25
  • 37
Aszmel
  • 1
  • 2
  • 1
    Possible duplicate of [How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Łukasz Rogalski Sep 18 '16 at 19:20

3 Answers3

1

You’re returning turn in next_player():

def next_player(turn):
    if turn == 'X':
        turn = 'O'
    if turn == 'O':
        turn = 'X'
    return turn # <<< Here.

If you want to assign the new turn, try doing this:

turn = next_player(turn)

instead of:

next_player(turn)
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
1
def next_player(turn):
if turn == 'X':
    turn = 'O'
if turn == 'O':
    turn = 'X'
return turn

Where is this variable return being saved? I don't believe it is updating your 'turn' variable, hence why you are just printing 'X' over and over.

DNSH
  • 11
  • 3
0
  1. second "if" should be an "elif". Look at your code, you are returning always "X" right now.
  2. the variable "turn" is not a global variable. if you pass next_player "turn" as an argument, you are copying the value of the variable "turn" implicitly. The variable "turn" inside the function is not the same as the variable "turn" outside the function!

To get the correct value from next_player(turn): turn = next_player(turn)

DaOnlyOwner
  • 343
  • 3
  • 8