About the return expression

Level: Beginner

The following code will print "False"

def function(x):
    if len(x) == 5: return True
    else: return x[0] == x[-1]

print function('annb')

why is the string "else: return x [0] == x [-1]" print False? I really understand what is happening, but I am having difficulty with this simple English language ... how can this behavior be described?

Is this a commonly used “technique”?

I first came across this particular syntax trying to solve a re-interview. It seems that the only way to do recursion is to use this shorthand approach:

def isPalindrome(s):
 if len(s) <= 1: return True
 else: return s[0] == s[-1] and isPalindrome(s[1:-1])

print isPalindrome('anna')

thanks Baba

+3
source share
3 answers

Sorry, I don’t quite understand what you mean, but think of it this way:

return (x[0] == x[-1])

, , , , ? :

if x[0] == x[-1]

, , , , , , x [0] [-1].

:

if x[0] == x[-1]: # if this is true
    return True # then return true
else:
    return False

, , , , , , , :

return x[0] == x[-1]

, .

EDIT. (x[-1]), Python "", x[0] "left" -to-right ', , x[-1] , " ".

+6

, , x[-1]. , x[-1] == 'b'. , x[0] == 'a', False.

+1

: x 5, True else, , True, else return False

else condition... else return False , False, False -False-. , . if:

def function(x):
    if len(x) == 5: return True
    else: return x[0] == x[-1]

def funcor(x):
    return (len(x)==5) or (x[0] == x[-1])

def funcany(x):
    return any((len(x)==5, x[0] == x[-1]))

def funcverbal(sequence):
    ## sequence[0] is the first element of zero based indexed sequence
    ## endswith is string specific function so sequence must be string
    ## if it length is not 5
    return len(sequence)==5 or sequence.endswith(sequence[0])

## function is normal data type in Python, so we can pass it in as variable
def test(func):
    print('Testing %s function' % func)
    for value in ('12345','annb','ansa','23424242',('1','2','1'), 123, '131'):
        try:
            print ("%r -> %r" % (value,func(value)))
        except:
            print ("Failed to call function with " + repr(value))

    print(10 * '-'+'Finished testing '+str(func) + 10 * '-')

for thisfunction in (function, funcor, funcany, funcverbal):
    test(thisfunction)

( , -)

isPalindrome , , , "anna" :

, "anna" 2 (1 0), , 'a' 'a', , isPalindrome 'nn'

, "nn" 2 (1 0), , 'n' 'n', , isPalindrome ''

, '' 2 (1 0), . , .

, , , .

def isPalindrome(s):
    return s==s[::-1]
0

Source: https://habr.com/ru/post/1761825/


All Articles