Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (18.4k points)

I'm working on a tic-tac-toe game that functions by replacing hyphens in a list with X's and O's to form a grid. I'm also a beginner when it comes to python, so this code is going to be clunky. The issue is that I want the game to be re-playable, but I can't find a way to reset the list to the hyphens I had at the start. Here's a simplified bit of code that better illustrates the problem:

list = ["-","-","-", "X","O"]

def replace():

    list[0] = list[3]

def main():

    replace()

    play_again = input ("play again?")

    if play_again == "yes":

        main()

    else:

        exit()

  main()

This makes the list go from ["-","-","-", "X","O"] to ["X","-","-", "X","O"], which makes the game work.

What I'd like to be able to do is somehow turn list back into ["-","-","-", "X","O"] when the player plays again. Unfortunately, the list seems to be stuck at ["X","-","-", "X","O"]. I've tried:

  1. adding list = ["-","-","-", "X","O"] right above replace()
  2. adding list[0] = "-" right above replace()

And, neither of these options work.

Is it possible to reset the values of the list to what I had at the start? If so, how should I approach this?

1 Answer

0 votes
by (36.8k points)

The simplest change that makes your code "work" is:

def main():

    global list

    list = ["-","-","-", "X","O"]

    replace()

    play_again = input ("play again?")

    if play_again == "yes":

        main()

    else:

        exit()

(Though that's not how I would do this from scratch--but you've already indicated that clunky code is okay/expected, so I'm not going to try and fix it here.)

This will also work, and doesn't require the global declaration:

def main():

    list[:] = ["-","-","-", "X","O"]

    replace()

    play_again = input ("play again?")

    if play_again == "yes":

        main()

    else:

        exit()

Improve your knowledge in data science from scratch using Data science online courses

Browse Categories

...