python - I need python to to check if variable is an integer using the input() command
问题描述
I need python to check if a variable is an integer or not, then act accordingly.
Here is the pertinent code:
def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?\n\n"
"Please note: Only forklifts that have greater than 8,000 lbs. of lift capacity will qualify for this incentive.\n"
"**Forklifts do NOT need to be located at a port or airport to be eligible.**")
forklift_count = input("Enter in # of forklifts:")
if type(forklift_count) is int:
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
data_grab()
Currently, when the user actually types in an integer, it will automatically jump to ELSE instead of executing the code under IF.
Any thoughts?
解决方案
试试str.isdigit()
方法:
forklift_count = input("Enter in # of forklifts:")
if forklift_count.isdigit():
# Use int(forklift_count) to convert type to integer as pointed out by @MattDMo
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
从文档中:
str.isdigit()
如果字符串中的所有字符都是数字并且至少有一个字符,则返回 True,否则返回 False。
推荐阅读
- bash - 如果条件在Jenkinsfile的while循环中中断代码,编写脚本循环并中断直到满足条件
- typescript - 在 index.ts 中找不到导出 typescript 和 javascript 组件的声明文件
- php - 将 UTF-8 重音转换为格式错误的 ISO 重音
- android - 如何在 android tv 应用程序中将视图设置为可聚焦?
- payment-gateway - Stripe - 预付费用
- python - 执行 pip 安装时出现 Git rev-parse HEAD 错误
- c - VSC 上的 GDB 无法正确读取 xml
- python - 如何将 bash curl 请求转换为 python
- sql - 为同一列返回具有不同特定数据的行或使用 POSTGRESQL 返回 0 行
- macos - 如何摆脱 Metal MTLTexture 中的 alpha 通道?