首页 > 解决方案 > 用户输入给出“ValueError:int() 以 10 为基数的无效文字:”

问题描述

我一直在尝试编写一个不和谐的机器人来检查使用的输入和命令,并带有参数,但我想检查它是字符串还是数字。让我解释清楚:

在我的代码中:

@client.command()
async def create(ctx, *args): # create a lobby
    firstarg = (int)(args[0])
    if (firstarg >= 4 and firstarg <= 10):
        await ctx.send("Max players : " + args[0])
        return (0)
    else:
        await ctx.send("Error. Please enter a maximum number of players between 4 and 10.")
        return (84)

参数总是字符串,所以我想我可以将它们转换为整数并且它可以工作。但是,有一个问题。

当我在命令中使用除数字以外的任何内容时,不会显示任何错误消息,因为它无法将其转换为整数。

所以,我想知道是否有办法检查这个特定的错误,以及我将来会遇到的其他类型的错误是否相同。

我不确定如何“检查它是否是一个字符串,以及它是否没有将其转换为 int 并在其余代码中使用它”。

它可能不是 100% 清楚,所以如果有不清楚的地方请告诉我,我会尽力澄清。

谢谢。

标签: pythonerror-handlingdiscordbotsdiscord.py

解决方案


我认为你需要看看异常在 Python 中是如何工作的以及如何处理它们

在您的情况下,您需要捕获 ValueError,它会给出类似的结果:

@client.command()
async def create(ctx, *args): # create a lobby
    try:
      firstarg = (int)(args[0])
    except ValueError:
      # the string was not a number
      await ctx.send("Error. Please enter a number.")
      return (84)
    else:
      # the string was a number
      if (firstarg >= 4 and firstarg <= 10):
        await ctx.send("Max players : " + args[0])
        return (0)
      else:
        await ctx.send("Error. Please enter a maximum number of players between 4 and 10.")
        return (84)

推荐阅读