-1

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?

brooklynveezy
  • 105
  • 10
  • The library reference is a good place to check the functions you're using. You can see from the [input docs](https://docs.python.org/3/library/functions.html#input) that it always returns a string. Your type check is always going to fail. – Malcolm Aug 16 '21 at 21:30

2 Answers2

2

Try the str.isdigit() method:

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.")  

From the documentation:

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise.

Red
  • 26,798
  • 7
  • 36
  • 58
0

A beginner/possibly incomplete answer here, but you could wrap the input() with int().

forklift_count = int(input("Enter in # of forklifts:"))

input() returns a string so even if you enter an int it will treat as string unless you convert it.

  • That being said, if they enter something like 3.5 it may not work as expected. Perhaps then you could use float and then try to get the floor of the number and if that raises an exception due to non-numeric can do the else? – SequelSnake Aug 16 '21 at 21:29