0

I need to reject any numerical values in the string using try except

try:
    name = str(input('please enter a name: '))
except ValueError:
    print('error')
Moe
  • 95
  • 1
  • 2
  • 5

1 Answers1

1

Like this:

try:
    name = input('please enter a name: ')
    if any(i.isdigit() for i in name):
        raise ValueError('Name must not contain any digits')
except ValueError as e:
    print(e)
Nin17
  • 2,821
  • 2
  • 4
  • 14
  • Of course, just `if any(..): print('Name must not ...')` would be a lot simpler than the superfluous `try..raise..except` construction. – deceze Apr 17 '22 at 19:30
  • 1
    Op asked for using try except? – Nin17 Apr 17 '22 at 19:31
  • Yeah, whatever they did that for… I'd have expected the difficult bit being the `any..isdigit` part; if you need to turn this into an exception conditionally because it makes sense in your code, fine. Just this tiny snippet here as is makes no sense… – deceze Apr 17 '22 at 19:32