python - If 语句接受输入并接受整数
问题描述
我需要编写一个 if 语句来接受用户输入并接受整数。
这是代码,但它只采用指定的整数。
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
解决方案
有几种方法可以解决这个问题,因为我不确定您到底在寻找什么。他们来了:
如果您希望它们不是整数并且您对将输入转换为整数不感兴趣,请查看下面的内容,我使用了上述 isnumeric() 函数:
Python 3 回答如下:
enter_num=input('Please Enter a number: \n') # I am prompting the user #for input and the \n means new line so the user would enter a value on #the new line
if enter_num.isnumeric(): #if the value the user entered is a number #proceed into the if statement
print('You must have entered an integer value') # print this #statement out if the if statement conditon is true
我不确定你是否熟悉 try 块,所以我不会进入它,但这里有另一种方法(我也不确定你是否熟悉 isinstance() 函数):
number=int(input('Please Enter a number: \n')) #prompting the user for #a number
if isinstance(number,int): # if the vlaue is a integer enter the if #statement
print('this is an integer') #enters the if statement if its true
如果我的解决方案有帮助,我很抱歉。但也有这个问题可能会有所帮助: 如何在 python 2.7 中检查原始输入是否为整数?
推荐阅读
- postback - Grid 中的 ImageButton 不会触发回发,因此不会触发 rowcommand
- python - 使用 deepstack 构建用于图像二元分类的集成学习模型
- sql-server - EF Core 仅查询 DateTimeOffset 的 DateTime 无法翻译;
- python - 用于运行 Python 的 py.exe 的替代程序
- html - 为什么我的 box-shadow 不能正确重叠在这些 flex 孩子身上?
- sql - 未找到父键 ORA-06512: 在 "SYS.DBMS_SQL"
- python - 如何给列表一个索引名称?
- c++ - C++ 函数声明问题,错误 C2086。帮助我 CPP 大师
- flutter - 如何在 Flutter 中直接从 Play 商店创建这种类型的应用内评分?
- google-cloud-platform - 多个租户在 GCP 上访问 Confluent kafka