How can I make the computer take a fallback action when my for loop finds no valid move?
Asked by
_circuit breaker
I'm building a Python number game where the player and computer take turns adding 1โ10 to a running total. The first player to reach 100 wins. For part of the game, I want the computer to choose a number that makes the total end in 9โfor example, adding 6 to 23 to get 29. I'm using a for loop to search through the possible numbers, but when the total already ends in 9, the loop finds no match. The computer then appears to skip its turn or behaves incorrectly. I also want to avoid the computer adding repeatedly during one turn. How should I structure the loop and provide a fallback move when no number satisfies the rule?
Answers
You can still include a `for` loop for the assignment, but it does not have to be the computerโs only decision-making tool. Search for a valid move, store it in a variable, and use an `else` fallback if the search fails. For example: `move = None`; `for num in range(1, 11):`; ` if (total + num) % 10 == 9 and total + num <= 100:`; ` move = num`; ` break`; `if move is None:`; ` move = random.randint(1, min(10, 100 - total))`; `total += move`. The important part is that `total += move` happens once, outside the search loop. That guarantees the computer gets one move and then the turn changes.
Reply to this answer
Be careful with operator precedence in the condition. `num + total % 10 == 9` is interpreted as `num + (total % 10) == 9`, not `(num + total) % 10 == 9`. Use parentheses around the complete sum. Also, if you want to handle the already-ending-in-9 case explicitly, test it before searching: `if total % 10 == 9:` followed by a normal random move; otherwise search for the number that makes the new total end in 9.
Reply to this answer
Your loop should select one move and then stop. As soon as you find a valid number, add it, print the result, and use `break`; otherwise the loop can keep changing the total or continue checking after the move. Also, `range(1, 11)` is needed because the upper limit is excluded, so `range(1, 10)` only checks 1 through 9. A simple version is: `move = None`; `for num in range(1, 11):`; ` if (total + num) % 10 == 9:`; ` move = num`; ` break`; `if move is None:`; ` move = random.randint(1, 10)`; `total += move`; `turn = 1`. When the total already ends in 9, no positive number may be needed to satisfy the rule, so the fallback should choose another legal move.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions