how to take integer input in python

# To prompt the user to input an integer we do the following:
valid = False

while not valid: #loop until the user enters a valid int
        x = int(input('Enter an integer: '))
        valid = True #if this point is reached, x is a valid int
    except ValueError:
        print('Please only input digits')

Here is what the above code is Doing:
1. We set valid to False. This is so that we can enter the while loop.
2. We enter the while loop. The condition is not valid. This means that as long as valid is False, we will stay in the loop.
3. We try to convert the input to an int. If it can’t be converted, then it will raise a ValueError exception.
4. If no exception is raised, then it means that the input can be converted to an int. So we set valid to True and break out of the loop.
5. If a ValueError exception is raised, then we print an error message and go back to the start of the loop.
6. Once we’ve broken out of the loop, we print x.