'second if statement returns result, first if statement doesn't
In the code below, the when check_result returns true, I want my program to terminate.
However, when check_result(p1) returns True the print statement prints, but the program carries on.
BUT if check_result(p2) returns True, the statement gets printed and program terminates. Please help me figure out why the first one doesn't work
Thanks!
while game_on:
p1_turn = int(input(f"Player 1, choose a number between 1 and 9\n"))
matrix[p1_turn - 1] = "X"
p1.append(p1_turn)
place_mark(matrix)
if check_result(p1):
print("Player 1 wins")
game_on = False
p2_turn = int(input(f"Player 2, choose a number between 1 and 9\n"))
matrix[p2_turn - 1] = "0"
p2.append(p2_turn)
place_mark(matrix)
if check_result(p2):
print("Player 2 wins")
game_on = False
Solution 1:[1]
just put a break statement. and the game_on variable is uneccessary. just use while 1 that is slightly faster than while True.
while 1:
p1_turn = int(input(f"Player 1, choose a number between 1 and 9\n"))
matrix[p1_turn - 1] = "X"
p1.append(p1_turn)
place_mark(matrix)
if check_result(p1):
print("Player 1 wins")
break
p2_turn = int(input(f"Player 2, choose a number between 1 and 9\n"))
matrix[p2_turn - 1] = "0"
p2.append(p2_turn)
place_mark(matrix)
if check_result(p2):
print("Player 2 wins")
break
Solution 2:[2]
if check_result(p1):
print("Player 1 wins")
game_on = False
Do you see any break statement here? The while loop won't break by itself.
if check_result(p1):
print("Player 1 wins")
game_on = False
break
You can anyway completely replace this game_on variable with a break statement:
if check_result(p1):
print("Player 1 wins")
break
if check_result(p2):
print("Player 2 wins")
break
If you want to know better the usage of break (and maybe of continue) read this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | XxJames07- |
| Solution 2 | FLAK-ZOSO |
