Skip to content Skip to sidebar Skip to footer

Validation For Int(input()) Python

def is_digit(x): if type(x) == int: return True else: return False def main(): shape_opt = input('Enter input >> ') while not is_digit(shap

Solution 1:

An easy way to test if an string is an int is to do this:

def is_digit(x):
    try:
        int(x)
        return True
    except ValueError:
        return False

Solution 2:

You must use try except when trying to convert to int. if it fails to convert the data inside int() then throw the exception inside except which in your case with makes the loop continue.

def is_digit(x):
    try:
        int(x)
        return True
    except:
        return False


def main():
    
    shape_opt = input('Enter input >> ')
    
    while not is_digit(shape_opt):
        
        shape_opt = input('Enter input >> ')
    else:
        print('it work')


if __name__ == '__main__':
    main()

Post a Comment for "Validation For Int(input()) Python"