Home > Software engineering >  See if input is a Integer in a Defined Function
See if input is a Integer in a Defined Function

Time:09-02

So I'm making this recipe converter program with Python that multiplies or divides your recipe by a certain number. I'm at a point where I made these few lines of code that check if the required amount for an ingredient is an integer or not:

while True:
    try:
        amount = int(input(f"Enter in the amount for {ingredient}: "))
    except ValueError:
        print("This is not a number")
        continue
    else:
        break

While this does work for checking if it's a number, I repeat this part of the code a few times throughout my program to check if a specific input is a number or not. Is there a way to make a defined function to check if it's an integer? For example (If it could be like this):

amount = int(input(f"Enter in the amount for {ingredient}: "))
check_int(amount)

CodePudding user response:

Factoring out the check alone won't do you much good (because you want to prompt again until they provide a valid int), so factor out both the check and the loop to a function:

def prompt_for_int(prompt_str=None, error_str='This is not an integer'):
    while True:
        try:
            return int(input(prompt_str))
        except ValueError:
            print(error_str, flush=True)

then at point of use you just see:

amount = prompt_for_int(f"Enter in the amount for {ingredient}: ")

CodePudding user response:

def check_int(value):

    try:
        int(value)
        return True
    except ValueError:
        return False
    
print(check_int(2))
print(check_int("2"))

A function that tries to cast the input value to be an integer. If it can cast it, it means that it is an integer, otherwise it is not an integer. If you want to handle floats too, you will need to make more changes to this.

  • Related