You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python铅笔游戏循环终止问题:如何正确跳出循环?

Fixing the Loop Termination Issue in Your Pencil Game

Let's break down why your loop isn't terminating correctly when the pencils hit 0, and walk through how to fix it:

What's Off with the Current Code

  1. Wrong Loop Condition: Your loop uses while number_of_pencil > 1 — this means even after the last pencil is taken (count hits 0), the code still tries to switch players and print a turn message, which shouldn't happen.
  2. Unconditional Player Switch: The player turn change runs every time through the loop, regardless of whether there are any pencils left to play for.
  3. Missing Initial Pencil Input: Your code references number_of_pencil but doesn't include the initial input prompt for it (I'll add that back to match your example flow).

Corrected Code

# Get starting pencil count first
number_of_pencil = int(input("How many pencils would you like to use: > "))
person = input("Who will be the first (John, Jack): > ")

while number_of_pencil > 0:
    # Print remaining pencils
    print("|" * number_of_pencil)
    # Prompt for input with proper format
    pencil_taken = int(input(f"{person}'s turn: > "))
    # Subtract the taken pencils from the total
    number_of_pencil -= pencil_taken
    
    # Exit loop immediately if no pencils are left
    if number_of_pencil == 0:
        break
    
    # Switch players only if there are still pencils left to play
    person = "Jack" if person == "John" else "John"

Key Fixes Explained

  • Updated Loop Condition: Now we loop only while number_of_pencil > 0 — this aligns with the game's logic: stop when there's nothing left to take.
  • Early Loop Exit: Right after updating the pencil count, we check if it's 0. If yes, we use break to exit the loop immediately, so no extra turn message is printed.
  • Proper Input Prompt: The input now includes the : > suffix to match your example's output style.
  • Concise Player Switch: Used a ternary operator to simplify the player toggle logic (optional, but makes the code cleaner).

Test Output (Matching Your Example)

How many pencils would you like to use: > 5
Who will be the first (John, Jack): > John
|||||
John's turn: > 2
|||
Jack's turn: > 1
||
John's turn: > 2

This version terminates correctly the moment the last pencil is taken, with no unwanted extra turn messages.

内容的提问来源于stack exchange,提问作者Mustafa Anandwala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:17:37