9 Antworten
+ 11
# Create a global variable `A`.
A = 5
def impure_sum(b):
# Adds two numbers, but uses the
# global `A` variable.
return b + A
def pure_sum(a, b):
# Adds two numbers, using
# ONLY the local function inputs.
return a + b
print(impure_sum(6))
#11
print(pure_sum(4, 6))
#10
Thank you...Sooo much 😊
+ 6
Can you please little bit more explain about impure function, with sample program.??
+ 3
Pure function: does nothing to the outer program, just returns a value.
def pure(x):
return x * 3
Impure functions, however do stuff, too.
So, a lot of people use impure functions for not a good reason:
def impure(x):
print(x * 3)
This is not good, because sometimes you want to use the function in equations, for example:
i = pure(8) + 1
But you cannot do that with impure functions without disturbing the program.
+ 3
Because it outputs stuff on the screen. So you cannot quietly run the function 100 times without anyone noticing.
So, if you do
triples = [times3(x) for x in range(100)]
Then you might notice what I mean
+ 2
Impure functions somehow change the state of the program. So,
def times3(x):
print("Counting the three times", x, "...")
return x * 3
This is also an impure function (a very annoying one, if I must say). But impure functions don't necessarily have to output something:
timesCalled = 0
def times3(x):
timesCalled += 1
return x * 3
This is also impure.
I'm not sure if I can explain it more to you, it's pretty simple
+ 2
Well simply pure functions are functions, that only uses it's parameters to receive data from outside.
#Pure:
def f(x):
return x + 7
Inpure:
a = 15
def f(x):
return x + a
#Uses variable a, which was defined outside and not received as argument.