1
string = 'ABcD'
for letter in string:
    if letter.isupper():
        print (letter,end='')

In the above code, the output is ABD But when I write the code without parentheses after isupper, like so:

string = 'ABcD'
for letter in string:
    if letter.isupper:
        print (letter,end='')

the output is ABcD. Why doesn't python raise a syntax error here ; how does this work?

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Does this answer your question? [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – awesoon May 25 '20 at 10:01
  • Can you clarify your question? Why would you assume a syntax error here? This is valid syntax to refer to attributes. – MisterMiyagi May 25 '20 at 10:11

2 Answers2

3

isupper is an attribute of the string letter, therefore Python is fine with you accessing it.

>>> letter = 'a'
>>> letter.isupper
<built-in method isupper of str object at 0x0000028258E80170>

It's the method isupper of the string. You did not call it (no ()), but that's not a syntax error.

In a boolean context (if letter.isupper), Python checks whether bool(letter.isupper) is True or False.

>>> bool(letter.isupper)
True

Any method is "truthy" (bool returns True), so that's why the if block is entered.

timgeb
  • 76,762
  • 20
  • 123
  • 145
2

It's worth knowing that static analysis tools can be used to catch such mistakes. For example, with pylint:

test.py:2:0: W0125: Using a conditional statement with a constant value (using-constant-test)
Thomas
  • 174,939
  • 50
  • 355
  • 478