-2

So whilst programming part of my homework, I decided to include validation within my program. However whilst adding in validation using the .isalpha() command, when having a sentence with letters in it, I get the error message for when typing in numbers. Sorry, cant display all of my program but i have included a test bed of code I programmed to test whether the .isalpha() command works, for validating whether only alphabetic letters are entered. Test data entered = one of several testing examples

word = input("enter a word")
if word.isalpha():
    print("Word accepted")
else:
    print("Invalid letters only")
Kay
  • 797
  • 1
  • 6
  • 28

1 Answers1

2

If you enter more than one word, there are non-alpha characters in your input (spaces in the case of the input "testing example one of several"). Those cause isalpha to fail.

Also, your error message is misleading - a single non-alpha character is enough to trigger the error, not "invalid letters only".

In [1]: "Hello".isalpha()
Out[1]: True

In [2]: "Hello Hello".isalpha()
Out[2]: False

In [3]: "Lotsoflettersandonedigit1".isalpha()
Out[3]: False

If you want to allow spaces in your input as well (but no punctuation or digits or other non-letter characters), you could do

if all(s.isalpha() for s in word.split()):
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561