Blue_Wolf13 Blue_Wolf13 - 2 months ago 8
Python Question

Is there a way I can prevent users from entering numbers with input()

I would like to prevent the user from entering numbers to save troubles down the line in my program. I know how to use try, except with int(input()) to prevent strings being entered when integers are required but I was wondering if a similar thing was possible with str(input()).

For example, if the user was asked for their name and they entered, "1994", they would receive and error message for entering an integer.

Jim Jim
Answer

Use a try-except with an else block in which you'll raise a ValueError if an Exception didn't occur during conversion to an int (which means the input is an int:

v = input("> ")
try:
    _ = int(v)
except:
    pass
else:
    raise ValueError("input supplied should be of type 'str'")

This will catch any numbers entered by raising the exception in the else block:

> 1992

ValueErrorTraceback (most recent call last)
<ipython-input-35-180b61d98820> in <module>()
      5    pass
      6 else:
----> 7    raise ValueError("input supplied should be of type 'str'")

ValueError: input supplied should be of type 'str'

And allow strings by passing in the except:

> jim

v
Out[37]: 'jim'

Alternatively, you could also do this with any and isdigit:

v = input("> ")
if any(s.isdigit() for s in v):
    raise ValueError("input supplied should be of type 'str'")

This checks to see if any characters are digits and if so raises the error.


You could prevent floats too, but this starts to get ugly:

v = input("> ")
for f in [int, float]:
    try:
        _ = f(v)
    except:
        pass
    else:
        raise ValueError("Numbers not allowed")