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

求助:使用and语句制作石头剪刀布游戏遇循环异常问题

Troubleshooting Your Rock-Paper-Scissors Loop Stuck on Input

Hey there! Let's figure out why your game's stuck repeating the input question instead of moving forward. The and statement in your conditional check is almost certainly the culprit—here are the most common issues and fixes:

1. Mixed-Up Logical Operators (Using and When You Need or... or Vice Versa)

A super easy mistake is misusing and vs or in your input validation loop. For example, if you wrote something like this:

user_choice = input("Pick rock, paper, or scissors: ")
while user_choice != "rock" and user_choice != "paper" or user_choice != "scissors":
    user_choice = input("Invalid! Try again: ")

The problem here is operator precedence: and runs before or, so this condition simplifies to "if the input isn't rock AND isn't paper, OR if it isn't scissors". Since any input can't be all three at once, this condition is always True—so your loop never exits.

Fix:

Use and for all negative checks (or switch to a cleaner not in check):

# Correct and-based condition
user_choice = input("Pick rock, paper, or scissors: ")
while user_choice != "rock" and user_choice != "paper" and user_choice != "scissors":
    user_choice = input("Invalid! Try again: ")

# Even cleaner alternative
user_choice = input("Pick rock, paper, or scissors: ")
while user_choice.lower() not in ["rock", "paper", "scissors"]:
    user_choice = input("Invalid! Try again: ")

2. Ignoring Case Sensitivity

If your code checks for exact lowercase matches but the user inputs something like "Rock" or "PAPER", your and conditions will all evaluate to True (since "Rock" != "rock"), keeping the loop running.

Fix:

Normalize the input to lowercase (or uppercase) before checking:

user_choice = input("Pick rock, paper, or scissors: ").lower()
while user_choice != "rock" and user_choice != "paper" and user_choice != "scissors":
    user_choice = input("Invalid! Try again: ").lower()

3. Accidental Reverse Logic

Double-check that your loop condition is set to repeat only when the input is invalid. If you accidentally wrote a condition that's always True (like mixing up equality checks with and), the loop will never end.

Quick Debug Trick:

Print your condition's value right after input to see what's happening:

user_choice = input("Pick rock, paper, or scissors: ")
print(f"Condition result: {user_choice != 'rock' and user_choice != 'paper' and user_choice != 'scissors'}")

This will tell you if the condition is evaluating to True when it shouldn't.


内容的提问来源于stack exchange,提问作者Gareth Hamill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:34:04