The correct solution would use an or
.
string = input("Enter a string: ")
if all(x.isalpha() or x.isspace() for x in string):
print("Only alphabetical letters and spaces: yes")
else:
print("Only alphabetical letters and spaces: no")
Although you have a string, you are iterating over the letters of that string, so you have one letter at a time. So, a char alone cannot be an alphabetical character AND a space at the time, but it will just need to be one of the two to satisfy your constraint.
EDIT: I saw your comment in the other answer. alphabet = string.isalpha()
return True
, if and only if all characters in a string are alphabetical letters. This is not what you want, because you stated that you want your code to print yes
when execute with the string please
, which has a space. You need to check each letter on its own, not the whole string.
Just to convince you that the code is indeed correct (well, ok, you need to execute it yourself to be convinced, but anyway):
>>> string = "please "
>>> if all(x.isalpha() or x.isspace() for x in string):
print("Only alphabetical letters and spaces: yes")
else:
print("Only alphabetical letters and spaces: no")
Only alphabetical letters and spaces: yes
EDIT 2: Judging from your new comments, you need something like this:
def hasSpaceAndAlpha(string):
return any(char.isalpha() for char in string) and any(char.isspace() for char in string) and all(char.isalpha() or char.isspace() for char in string)
>>> hasSpaceAndAlpha("text# ")
False
>>> hasSpaceAndAlpha("text")
False
>>> hasSpaceAndAlpha("text ")
True
or
def hasSpaceAndAlpha(string):
if any(char.isalpha() for char in string) and any(char.isspace() for char in string) and all(char.isalpha() or char.isspace() for char in string):
print("Only alphabetical letters and spaces: yes")
else:
print("Only alphabetical letters and spaces: no")
>>> hasSpaceAndAlpha("text# ")
Only alphabetical letters and spaces: no
>>> hasSpaceAndAlpha("text")
Only alphabetical letters and spaces: no
>>> hasSpaceAndAlpha("text ")
Only alphabetical letters and spaces: yes