python - 用户输入给出“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% 清楚,所以如果有不清楚的地方请告诉我,我会尽力澄清。
谢谢。
解决方案
我认为你需要看看异常在 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)
推荐阅读
- python - Can someone help me find a solution to error source in my code?
- graphics - How to get the color of a specific pixel drawn using SDL_RenderDrawPoint() on SDL2?
- python - Tensorflow preprocessing split string to chars
- python-3.x - loop over dict key-value-pair or each element in dict
- python - 按顺序发布最有趣的流派 - python app
- python - 如何根据标题值删除列?
- react-native - What's the correct way to transpile react-native to use with nodejs?
- php - Laravel 5.8:从空值创建默认对象
- python - 矩阵(列表)的元素总和,但仅在另一个矩阵(列表)中给出的索引处
- css - 如何在 P 类标签之后添加样式