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

石头剪刀布游戏Bug:合法输入仍触发‘Invalid input’提示

问题:合法输入仍触发"Invalid input"提示

你的代码中无效输入判断的逻辑条件错误,导致无论输入rock、paper还是scissors,都会触发"Invalid input"的打印。

问题原因

这段判断条件:

if player_choice != "rock" or player_choice != "paper" or player_choice != "scissors":
    print("Invalid input")

逻辑上永远为真。因为当你输入rock时,player_choice != "paper"和player_choice != "scissors"都是真,or只要有一个条件为真整个表达式就为真;同理输入paper或scissors时,另外两个不等于的条件也会成立,所以每次都会执行打印。

解决方案

你需要把判断逻辑改成同时不满足三个合法值时才判定为无效输入,有两种写法:

  1. 使用and替代or:
if player_choice != "rock" and player_choice != "paper" and player_choice != "scissors":
    print("Invalid input")
  1. 更简洁的写法:用not in检查输入是否不在合法列表中:
if player_choice not in ["rock", "paper", "scissors"]:
    print("Invalid input")

修正后的完整代码

import random

round_count = int(input("How many rounds would you like to play? "))
score = 0

for i in range(int(round_count)):
    computer_choice = random.choice(["rock", "paper", "scissors"])
    player_choice = input("Rock, Paper, Scissors? ").lower()

    if computer_choice == player_choice:
        print("Tie")
        # add_round_for_tie = input("Would you like to add a round because of the tie?")
        # if add_round_for_tie.lower() == "yes":
        # round_count += 1

    else:
        if computer_choice == "paper" and player_choice == "scissors":
            print("Scissors beats paper. You win!")
            score += 1
        if computer_choice == "scissors" and player_choice == "paper":
            print("Scissors beats paper. You lost.")
        if computer_choice == "rock" and player_choice == "scissors":
            print("Rock beats scissors. You lost.")
        if computer_choice == "scissors" and player_choice == "rock":
            print("Rock beats scissors. You win!")
            score += 1
        if computer_choice == "paper" and player_choice == "rock":
            print("Paper beats rock. You lost.")
        if computer_choice == "rock" and player_choice == "paper":
            print("Paper beats rock. You win!")
            score += 1

    # 修正后的无效输入判断
    if player_choice not in ["rock", "paper", "scissors"]:
        print("Invalid input")

print(f"Your score is {score}/{round_count}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:56:19