You need to enable JavaScript to run this app. Python3开发小游戏时如何检测用户输入是否为非整数
优惠活动
大模型
产品
解决方案
定价
更多

Python3开发小游戏时如何检测用户输入是否为非整数

石头剪刀布游戏输入崩溃问题修复

现有代码的问题定位

  • 程序崩溃触发点:代码直接将用户输入传入int()转换,没有做异常拦截,只要用户输入非整数内容,就会抛出ValueError直接终止运行,完全走不到后续的输入错误判断分支
  • 原有输入错误判断逻辑完全无效:代码最后写的elif user_choice != int or user_choice == ValueError 存在本质逻辑错误:
    • int是Python内置的整数类型对象,不是具体数值,拿转换后的user_choice和类型做比较,判断结果永远为假
    • 转换int的步骤已经报错崩溃,根本不会执行到这段判断逻辑,自然无法弹出输入错误的提示

适配场景的修复实现

不需要额外拼接复杂的字符串判断逻辑,直接用Python原生的异常捕获机制处理输入校验,步骤如下:

  • 把读取输入、转整数的操作放进try-except块,捕获转换时抛出的ValueError
  • 校验转换后的数值是否在1-3的范围内,不符合的话给出提示,不占用当前回合计数
  • 等输入校验通过后,再执行后续的对战判断逻辑

核心修复代码片段:

while i < round_select:
    i += 1
    # 生成对手的随机选择
    opponent = random.randint(1, 3)
    time.sleep(0.2)

    # 输入校验逻辑
    user_input = input(
        """
(1)Paper, (2)Scissors, (3)Rock!: """
    )
    try:
        user_choice = int(user_input)
        # 校验数值范围
        if user_choice not in (1, 2, 3):
            print("请输入1、2或3对应的整数!")
            i -= 1  # 范围不合法,回退回合数
            continue
    except ValueError:
        print("输入无效,请输入1、2或3对应的整数!")
        i -= 1  # 非整数输入,回退回合数
        continue

    # 以下为原有对战逻辑,无需改动
    if user_choice == opponent:
        print(username + choice_to_text(user_choice))
        print("Opponent" + choice_to_text(opponent))
        print("Tie")
        ties += 1
    elif (user_choice == 1 and opponent == 2) or (user_choice == 2 and opponent == 3) or (user_choice == 3 and opponent == 1):
        print(username + choice_to_text(user_choice))
        print("Opponent" + choice_to_text(opponent))
        print("One point to the opponent!")
        opponent_score += 1
    elif (user_choice == 1 and opponent == 3) or (user_choice == 2 and opponent == 1) or (user_choice == 3 and opponent == 2):
        print(username + choice_to_text(user_choice))
        print("Opponent" + choice_to_text(opponent))
        print("One point to " + username + "!")
        user_score += 1

该方案不需要额外编写字符串判数字的正则逻辑,只要用户输入无法被转为整数、或者转换后数值不在1-3范围内,都会被拦截,不会触发程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 21:27:04