Reputation: 43
This is a basic game just like rock paper scissor but with different names, I also apologize for the commentless code. I'm almost getting to the end of my code, but I'm having a tough time with the while loop. I have all on my statements done, but how do I implement a while loop? I want the game to run again after I finish it so it will ask me for another input. If I run this, it is waiting to give me an answer, but never does, since it is an infinite loop.
import random
def pythonRubyJava():
gameList = ["python","ruby","java"]
userInput = raw_input("python, ruby, or java?:")
randomInput = random.choice(gameList)
print randomInput
while True:
if userInput not in gameList:
print "The game is over"
elif userInput == randomInput:
print "stalemate"
elif userInput == "python" and randomInput == "ruby":
print "You win!"
elif userInput == "ruby" and randomInput == "java":
print "You win!"
elif userInput == "java" and randomInput == "python":
print "You win!"
elif userInput == "python" and randomInput == "java":
print "You Lose!"
elif userInput == "ruby" and randomInput == "python":
print "You Lose!"
elif userInput == "java" and randomInput == "ruby":
print "You Lose!"
Upvotes: 0
Views: 2765
Reputation: 59974
Instead of using a while loop in the function, just call the function again! Remove the while loop from your function.
Outside the function, you can do something like:
pythonRubyJava() # Call the function first
while 1:
ans = raw_input('Do you want to play again? Y/N ')
if ans == 'Y':
pythonRubyJava()
else:
print "bye!"
break # Break out of the while loop.
Upvotes: 2
Reputation: 1097
import random
def pythonRubyJava():
gameList = ["python","ruby","java"]
userInput = raw_input("python, ruby, or java?:")
randomInput = random.choice(gameList)
print randomInput
while True:
if userInput not in gameList:
print "The game is over"
[change the while boolean statement in here]
elif userInput == randomInput:
print "stalemate"
elif userInput == "python" and randomInput == "ruby":
print "You win!"
elif userInput == "ruby" and randomInput == "java":
print "You win!"
elif userInput == "java" and randomInput == "python":
print "You win!"
elif userInput == "python" and randomInput == "java":
print "You Lose!"
elif userInput == "ruby" and randomInput == "python":
print "You Lose!"
elif userInput == "java" and randomInput == "ruby":
print "You Lose!"
pythonRubyJava():
This way it would run again, and show the result.
Upvotes: -1
Reputation: 21435
You should move
userInput = raw_input("python, ruby, or java?:")
randomInput = random.choice(gameList)
inside the while
loop so that the inputs are regenerated each time the loop is run.
Upvotes: 3