首页 > 解决方案 > 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?

标签: pythonif-statementinputinteger

解决方案


试试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。


推荐阅读