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

求助:修复石头剪刀布小程序的首字母大写兼容问题

解决石头剪刀布程序的大小写兼容问题

你的问题根源是字符串匹配严格区分大小写,当输入首字母大写(比如Rock)时,无法和代码里的小写字符串("rock")匹配,导致程序进入错误分支或无法正确判断胜负。

最简单的解决方式是将用户输入统一转换为小写,这样不管用户输入什么大小写格式,都能和预设的选项匹配。具体修改如下:

  1. 获取用户输入时,调用lower()方法转换为小写:
user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ").lower()
  1. 后续所有判断逻辑无需修改,因为输入已经统一为小写,能和代码里的"rock"、"paper"、"scissors"正常匹配。

修改后的完整代码:

# Rock Paper Scissors

import time
import random

user_wins = 0
computer_wins = 0

def RockPaperScissors():
    # 将输入转换为小写,兼容大小写输入
    user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ").lower()

    if user_choice == "rock" or user_choice == "paper" or user_choice == "scissors":
        print("Good choice, lets see who wins.")
        time.sleep(1.5)
    else:
        print('Please enter either "rock", "paper", or "scissors"')

    computer_choice = ["rock", "paper", "scissors"]
    rand_choice = random.choice(computer_choice)

    print("The computer chose", rand_choice)

    if user_choice == "rock" and rand_choice == "scissors":
        print("You won!")
    elif user_choice == "scissors" and rand_choice == "rock":
        print("The computer won, try again.")
    elif user_choice == "paper" and rand_choice == "rock":
        print("You won!")
    elif user_choice == "rock" and rand_choice == "paper":
        print("The computer won, try again")
    elif user_choice == "scissors" and rand_choice == "paper":
        print("You won!")
    elif user_choice == "paper" and rand_choice == "scissors":
        print("The computer won, try again")
        

RockPaperScissors()

这样修改后,用户输入Rock、ROCK、rOcK等任何大小写组合,程序都能正确识别并处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:15:33