How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check. Then program should check if input given by user be
For your use, using the .isdigit()
method is what you want.
For a given string, such as an input, you can call string.isdigit()
which will return True
if the string is only made up of numbers and False
if the string is made up of anything else or is empty.
To validate, you can use an if
statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string ""
causes .isdigit()
to return False
, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.