首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果用户输入的是字符串而不是整数,则发生异常

如果用户输入的是字符串而不是整数,则发生异常
EN

Stack Overflow用户
提问于 2020-06-16 03:19:49
回答 1查看 48关注 0票数 0

如果用户输入的是字符串而不是整数,我正在尝试让我的程序打印(无效输入,请重试)。

代码语言:javascript
复制
num_dice = 0
while True:
   if num_dice < 3 or num_dice > 5 or num_dice:
       num_dice = int(input("Enter the number of dice you would like to play with 3-5 : "))
       print("")
       print("Please enter a value between 3 and 5.")
       print("")
       continue
   else:
       break 
EN

回答 1

Stack Overflow用户

发布于 2020-06-16 03:25:56

您可以简单地使用isnumeric关键字来检查它是否是绝对数。

示例:

代码语言:javascript
复制
string1="123"
string2="hd124*"
string3="helloworld"

if string1.isnumeric() is True:
    #Proceed with your case.
    inputs=string1

文档参考: https://www.w3schools.com/python/ref_string_isnumeric.asp

附注:这将要求您将输入更改为字符串格式,因为isnumeric仅验证字符串。

我的意思是下面这部分。

num_dice = str(input("Enter the number of dice you would like to play with 3-5 : "))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62395409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档