2

I've defined my code to ensure all letters inside a loop are indeed letters with

if letter.isalpha() != True:
    return 'Failed'

This works. However, for what I'm doing we are strictly instructed to not compare Boolean values to True/False using ==, and with the way I'm doing it it's basically the same thing. Is there another way of doing this?

Sundrah
  • 785
  • 1
  • 8
  • 16
  • Negation: http://stackoverflow.com/questions/17168046/python-how-to-negate-value-if-true-return-false-if-false-return-true – Alex K. Apr 13 '15 at 14:39
  • are those letters coming from a word? – Padraic Cunningham Apr 13 '15 at 14:42
  • @Padraic yes they are. The actual function I'm doing this in is significantly more complex and this irons out most of the irrelevant words. – Sundrah Apr 13 '15 at 14:46
  • @Alex K is the actual term for this sort of thing referred to as negation? – Sundrah Apr 13 '15 at 14:46
  • You know you can simply call it on the word yes? `"foo".isalpha() -> True` `"foo!".isalpha() -> False` – Padraic Cunningham Apr 13 '15 at 14:47
  • Oh, I wasn't thinking. I typed that in after a few tests failed and this was one of the reasons as to why. Thanks for pointing that out. – Sundrah Apr 13 '15 at 14:48
  • Just for reference, using `==` and `!=` with `True` is strongly discouraged by [PEP 8](http://www.python.org/dev/peps/pep-0008/). The same goes for `False`. You should always use `if value:` or `if not value:` instead. –  Apr 13 '15 at 14:49
  • 1
    @iCodez Yeah cheers. I was wondering why my university coding guide told me to not use it which lead me to asking this question. – Sundrah Apr 13 '15 at 14:51

3 Answers3

4

Just do

if not letter.isalpha():
    return 'Failed'
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

isalpha() method returns boolean value, so you don't need to compare with != True. So you can just use not negation.

mchfrnc
  • 5,243
  • 5
  • 19
  • 37
0

Like Rafael said, letter.isalpha() returns a boolean. You can negate it using not.

(edit) Answer:

if not letter.isalpha():
    return 'Failed'
H.M. Prins
  • 11
  • 1