0

I would like to pass in 3 conditions to the function "check" to apply to str1, in this case the output should be [False, False, True]:

def check(conditions):
    str1 = '/'
    print(conditions)

check(conditions=[str1.find('//www.fao.org')!=-1, str1.find('//fao.org')!=-1, str1[0]=='/'])

However, before even calling the function it runs an error:

NameError: name 'str1' is not defined

Because this means that the conditions are executed even before the function check can be executed, how can I pass these conditions as arguments?

ardito.bryan
  • 429
  • 9
  • 22
  • 1
    variable str1 is in the function scope in this case. Move it out to a global scope if you want. – Kris Nov 17 '21 at 13:26
  • 1
    If you want to define a function to be evaluated against str1, define it as... well, _a function_, so `check()` can pass `str1` to it. – Charles Duffy Nov 17 '21 at 13:27

1 Answers1

7

Pass a list of functions to call on str1:

def check(conditions):
    str1 = '/'
    for f in conditions:
        print(f(str1))

check(conditions=[lambda x: x.find('//www.fao.org') != -1, lambda x: x.find('//fao.org') != -1, lambda x: x[0] == '/'])
chepner
  • 497,756
  • 71
  • 530
  • 681