0

I created 2 different python files. The first file named "game.py" has the code:

h = int(input("Pick number 1 or 2: "))

def game():

    if h == 1:
        print ("You lose!")
    if h == 2:
        print ("You win!")

def play_again():

    rounds = input("Play again? (Y/N): ")
    if rounds == "Y":
        game()
    if rounds == "NO":
        print ("Game Over")

As shown, I have 2 functions in this file.

Then I created another file with my main function that calls these 2 functions. The following is the code inside it:

import game

def main():

    game.game()

    game.play_again()

main()

When I run this on the console, it prints "Pick number 1 or 2: ". But if I run it again, it prints "Play again? (Y/N): ".

How do I fix this so that it only prints "Pick number 1 or 2 : " whenever I run the code?

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
qlzlahs
  • 73
  • 2
  • 9
  • How do you run this on the console? What do you type to start the program? – Robᵩ Jul 22 '15 at 21:30
  • I'm using Spyder 3.4 so I just have to run it. I don't have to type anything. @Robᵩ – qlzlahs Jul 22 '15 at 21:34
  • The `input` line is executed only during the first `import game` of each Python session. I guess that Spyder doesn't start a new Python session when you "just run it." How to fix it depends upon why that code is there. Tell us more about why you placed that code outside of a function. – Robᵩ Jul 22 '15 at 21:40
  • I have run your code using spyder and it works fine, where do you see the output when you run your code? – Padraic Cunningham Jul 22 '15 at 22:09

1 Answers1

0

maingame.py:

import game

game.game()

if __name__ == "__main__":
    print("maingame.py is being run directly")
else:
    print("maingame.py is being imported into another module")

game.py:

def game():
    h = input("Pick number 1 or 2:\n")
    if h == 1:
        print("You lose!")
    if h == 2:
        print("You win!")
    play_again()

def play_again():
    rounds = raw_input("Play again? (Y/N): ") # just use input() for python3
    if rounds == 'Y':
        game()
    if rounds == 'N':
        print("Game Over")

See also: What does if __name__ == "__main__": do?

and: Python 2.7 getting user input and manipulating as string without quotations

You can delete the three bottom lines from maingame.py but you should read the associated link to understand what if __name__ == "__main__": does and why. Normally you would just write:

if __name__ == "__main__":
    main()

And this will ensure that your file will run, beginning with main(), when called from the command line.

Community
  • 1
  • 1
Chris Hanning
  • 123
  • 1
  • 7