0

I understand how it's work, but how I can do that python print true and false in this case?)

def f(func, value):
        global a
        a = 2
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)
  • 3
    I understand what this code is doing, but not what your question is in regards to. Maybe another example would help? – Samwise May 29 '20 at 17:41
  • x == a take a as reference, but I need the value of a – Роман Намор May 29 '20 at 18:00
  • The value of `a` changed because you declared it as a global and then changed it from inside your function. What you were trying to accomplish instead? – Samwise May 29 '20 at 18:02
  • I have a global value `a`, well, I need to remember the current value, so that if it suddenly changes `lambda` doesn’t change – Роман Намор May 29 '20 at 18:09
  • Don't use a global value? With normal scoping you get exactly that behavior. It's only doing things you don't want because you declared it as a `global`, which is generally discouraged. – Samwise May 29 '20 at 18:10
  • https://stackoverflow.com/questions/12423614/local-variables-in-nested-functions – user2357112 May 30 '20 at 01:22

1 Answers1

0

If your goal is to have the code check the value of a that you originally declared (i.e. 3) so that it prints True;False instead of the inverse, just don't set a to 2 inside your function:

def f(func, value):
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)

Using global is generally not recommended because it makes it very easy to confuse yourself by having values change in unexpected ways.

Samwise
  • 68,105
  • 3
  • 30
  • 44