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?
3 Answers
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.
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.
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.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically