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

Python编写的石头剪刀布游戏部分if语句失效问题求助

石头剪刀布游戏问题排查与修复

你的代码核心问题有两个:

1. 输入大小写不匹配

比如用户输入Rock、YES这类带大写的内容时,代码里的字符串判断(比如userInput == "paper")会因为大小写不一致而不生效,看起来像是if语句没运行。

2. 未处理无效输入

如果用户输入了非rock/paper/scissors的内容,所有胜负判断的if都不会触发,会让你误以为是if语句失效。

修复后的代码

import random

moves = ('rock', 'paper', 'scissors')
while True:
    print("rock, paper, scissors. Go! ")
  
    # 统一转为小写并去除首尾空格,兼容大小写输入
    userInput = input("Choose your move: ").strip().lower()
    
    # 处理无效输入,提示重新选择
    if userInput not in moves:
        print("Invalid move! Please choose rock, paper, or scissors.")
        continue
  
    botInput = random.choice(moves)

    # 用elif替代多个独立if,避免冗余判断
    if userInput == botInput:
        print(f"{userInput} VS {botInput}")
        print("DRAW")
    elif (userInput == "paper" and botInput == "rock") or \
         (userInput == "scissors" and botInput == "paper") or \
         (userInput == "rock" and botInput == "scissors"):
        print(f"{userInput} VS {botInput}")
        print("Player Wins!")
    else:
        # 剩下的情况都是bot赢,不用再写多个if
        print(f"{userInput} VS {botInput}")
        print("Bot Wins!")
    
    print("Wanna Rematch?")
    # 同样统一处理输入大小写
    decision = input("Yes or No? ").strip().lower()
    if decision == "no":
        break
    # 输入yes或者其他内容,都继续循环

关键修改点

  • 对userInput和decision使用.strip().lower(),统一输入格式,解决大小写问题
  • 增加无效输入的判断,避免因输入错误导致的判断失效
  • 将多个独立if改为elif和else,简化逻辑,减少不必要的条件判断
  • 使用f-string替代字符串拼接,让代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:30:54