How to better understand Pure and impure Function in Python. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

How to better understand Pure and impure Function in Python.

How to deeply understand about Python functional programming.

24th Aug 2019, 1:56 PM
Harish Gajjar
Harish Gajjar - avatar
7 Answers
+ 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 😊
24th Aug 2019, 3:56 PM
Harish Gajjar
Harish Gajjar - avatar
+ 6
Can you please little bit more explain about impure function, with sample program.??
24th Aug 2019, 2:07 PM
Harish Gajjar
Harish Gajjar - avatar
+ 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.
24th Aug 2019, 2:01 PM
Airree
Airree - avatar
+ 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
24th Aug 2019, 2:22 PM
Airree
Airree - avatar
+ 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
24th Aug 2019, 2:13 PM
Airree
Airree - avatar
+ 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.
24th Aug 2019, 2:36 PM
Seb TheS
Seb TheS - avatar