-4

How do i put this in a loop in python so that it keeps asking if player 1 has won the game, until it reaches the number of games in the match. i tried a while loop but it didn't work :(

Y="yes"
N="no"
PlayerOneScore=0
PlayerTwoScore=0

NoOfGamesInMatch=int(input("How many games? :- "))
while PlayerOneScore < NoOfGamesInMatch:
    PlayerOneWinsGame=str(input("Did Player 1 win the game?\n(Enter Y or N): "))

if PlayerOneWinsGame== "Y":
     PlayerOneScore= PlayerOneScore+1
else:
     PlayerTwoScore= PlayerTwoScore+1

print("Player 1: " ,PlayerOneScore)
print("Player 2: " ,PlayerTwoScore)

print("\n\nPress the RETURN key to end")
Amz x
  • 1
  • 1
  • 2
    Where is the `while` loop, and what precisely does *"it didn't work"* mean? – jonrsharpe Jan 06 '15 at 14:54
  • hi, i added a while loop and it didn't work means i cant end the loop, it keeps on repeating did player 1 win the game?! sorry for the horrid explanation – Amz x Jan 07 '15 at 17:57
  • 1
    Please note that **indentation matters in Python**. Your `if` test is not inside the `while` loop. Consider reading a Python tutorial. – jonrsharpe Jan 07 '15 at 18:07

2 Answers2

0

A while loop will work just fine

while PlayerOneScore < NoOfGamesInMatch:
    PlayerOneWinsGame=str(input("Did Player 1 win the game?\n(Enter Y or N): "))

    if PlayerOneWinsGame== "Y":
        PlayerOneScore= PlayerOneScore+1
    else:
        PlayerTwoScore= PlayerTwoScore+1

Keep everything else out of the loop. Meaning keep your initialization stuff before the loop, then your score reporting after the loop.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • hi, thanks for the answer. It works!! but how would i end the loop because it will just keep repeating Did player 1 win the game. – Amz x Jan 07 '15 at 17:54
  • The loop will only end once `PlayerOneScore` is equal to or greather than `NoOfGamesInMatch` – Cory Kramer Jan 07 '15 at 18:02
0
import sys    
while PlayerOneScore < NoOfGamesInMatch:
    answer = str(input("Did Player 1 win the game?\n(Enter Y or N or Q to quit): "))

    if answer.lower() == "q":
        sys.exit()
    elif answer.lower() == "y":
        PlayerOneScore = ( PlayerOneScore + 1 )
    elif answer.lower() == "n":
        PlayerTwoScore = ( PlayerTwoScore + 1 )
    else
        print "Valid answers are Y (yes), N (no) and Q (quit).

You can now leave the game by entering q. I also made it so that the answers are not case sensitive.

The game will be going as long as PlayerOneScore is smaller than NoOfGamesInMatch.

You should place the import sys at the top of the file.

alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
  • [You should not use `is` for these types of comparisons, you should use `==`](http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs) – Cory Kramer Jan 07 '15 at 19:07