0

hi so i had a doubt in python:

def check(message):
    if len(message)==0 or message[0]==message[-1]:
        return True
    else:
        return False
print(check('else'))
print(check('tree'))
print(check(""))

this works.

def check(message):
    if message[0]==message[-1] or len(message)==0:
        return True
    else:
        return False
print(check('else'))
print(check('tree'))
print(check(""))

this doesn't. why? emphasis on the 'if' function in the check function.

  • Nit pick: both *work* perfectly. But the first protects fromempty input since or shirt circuits – 2e0byo Jan 08 '22 at 15:44
  • https://stackoverflow.com/questions/13960657/does-python-evaluate-ifs-conditions-lazily – azro Jan 08 '22 at 15:44

1 Answers1

2

It is because or short-circuits: it doesn't evaluate the right argument if there's no need to judging by the value of the left argument.

Eg if a==0 or f() will not execute f() if a is 0 and thus it makes no difference for the result if f() evaluates to True or False.

Antony Hatchkins
  • 31,947
  • 10
  • 111
  • 111