-
Notifications
You must be signed in to change notification settings - Fork 0
/
Functions.py
800 lines (620 loc) · 19.6 KB
/
Functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# '''
# * It is a group of statements is repeatedly required then it is not recommended to write these statements
# everytime seperately.
# * We have to define these statements as a single unit and we can call that unit any
# number of times as per our requirement without re-writting.
# This unit is nothing but a function.
# * The main advantage of functions is code reusability.
# Note:
# * In other languages functions are known as methods,procedures,subroutines,etc..........
# ****************************** Types of Functions **********************
# 1. Built-in Functions:
# * The functions which are coming along with python software automatically,are called as bulit-in functions (or) pre-defined function.
# Example : id(),type(),input(),eval(), etc....................
# 2. User Defined Functions:
# * The functions which are developed by programmers explicitly according to business requirements,are called as user defined funcions.
# Syntax :
# def function_name(parameter):
# statements
# statements
# statements
# return value
# Parameters:
# -----------
# * Parameters are inputs to the function. If the function contains parameter,then at the time
# of calling ,compulsory we should provide values,otherwise we will get an error.
# Return statement:
# ----------------
# * Function can take input as parameter and executes business logic , and returns output to the caller within the return statement.
# * If we are not writing return statement then default return value is None.
# Returning multiple values from a function :
# -------------------------------------------
# * In other languages like c,c++ and java functions can return atmost one value.
# * But in python we can return multiple values from a function.
# '''
# # Example 1:
# def wish():
# print("Hello Good Morning")
# wish()
# # Parameter example :
# def wish(name):
# print("Hello Good Morning",name)
# wish("Vijay")
# wish("venkata")
# def wish(name):
# print("Hello Good Morning",name)
# print(wish("Vijay")) # None
# print(wish("venkata")) # None
# # W.A.P a function to take number as input and print its square value.
# def squareit(num):
# print("The square of ",num,"is",num*num)
# squareit(4)
# squareit(5)
# # Return statement example :
# def add(x,y):
# return x+y
# result = add(10,20)
# print('The sum is:',result)
# print('The sum is:',add(100,200))
# def f1():
# print('Hi')
# print(f1())
# # W.A function to check whether the given number is even or odd?
# def even_odd(num):
# if num%2==0:
# print(num,"is even number")
# else:
# print(num,"is odd number")
# even_odd(10)
# even_odd(15)
# # W.A.P a function to check whether the given number is prime or not?
# def is_prime(num):
# for i in range(2,num):
# if num%i==0:
# print(num,"is not prime number")
# break
# else:
# print(num,"is prime number")
# is_prime(10)
# is_prime(3)
# # W.A.P a function to print all prime numbers between 1 to 100?
# def is_prime(num):
# for i in range(2,num):
# if num%i==0:
# break
# else:
# print('The prime numbers are:',num)
# for i in range(1,101):
# is_prime(i)
# # W.A a function to find the factorial of a given number.
# def fact(num):
# result = 1
# while num>=1:
# result = result * num
# num = num - 1
# return result
# # print("The factorial of 5 is:",fact(5))
# for i in range(1,6):
# print("The factorial of",i,"is:",fact(i))
# # -------------------> Returning multiple values Example.
# def sum_sub(a,b):
# sum = a+b
# sub = a-b
# return sum,sub
# x,y = sum_sub(100,50)
# print("The sum is:",x)
# print("The sum is:",y)
# def calc(a,b):
# sum = a+b
# sub = a-b
# mul = a*b
# div = a/b
# return sum,sub,mul,div
# x = calc(100,50)
# print(type(x))
# print("The results are:")
# for i in x:
# print(i)
# '''
# --------------------------- Types of args --------------------------
# def f1(a,b):
# -----
# -----
# -----
# f1(10,20)
# -->a,b are formal args where as 10,20 are actual args.
# There are 4-types of actual args are allowed in python.
# 1.positional args
# 2.keyword args
# 3.default args
# 4.variable length args
# 1.positional args:
# -------------------------
# These are the args passed to function in correct positional order.
# -->The number of args and position of args must be matched. If we change the order then result may be chaned.
# -->If we change the number of args then we will get an error.
# sub(10) #sub() missing 1 required positional argument: 'b'
# sub(10,20,30)#sub() takes 2 positional arguments but 3 were given
# 2).keyword args:
# ------------------------
# We can pass argument values by keyword i.e by parameter name
# def wish(name,msg):
# print('Hello',name,msg)
# wish(name='sunny',msg='good evening....')
# wish(msg='good evening....',name='sunny')
# -->Here the order of args is not important but number of args must be matched.
# Note:
# We can use both positional and keyword args simultaneously. But first we have to take positional args and then keyword args, otherwise we will get an error.
# 3).default args:
# ----------------
# * Sometimes we can provide default values for our positional args.
# Ex:
# def wish(name='radhika'):
# print('Hello',name,'good evening.....')
# wish()
# wish('lilly')
# * If we are not passing any name then only default value will be considered.
# 4).variable length args:
# ------------------------
# * Sometimes we can pass any number of args to our function, such type of args are called as variable length of args.
# * We can declare a variable length of args with '*' symbol as:
# def f1(*n):
# * We can call this function by passing any number of args including zero number , internally all these values represented in the
# form of tuple.
# Note:
# After variable length argument, if we are taking any other args then we should provide values as keyword args.
# Note:
# We can declare keyword variable length args also. For this we have to use **
# def f1(**n):pass
# We can call this function by passing any number of keyword args. Internally these keyword args will be stored inside a dict.
# '''
# # Example : 1 -----> [positional arguments]
# def sub(a,b):
# print(a-b)
# sub(10,20)
# sub(50,100)
# # Example : 2 -------> [keyword arguments]
# def wish(name,msg):
# print('Hello',name,msg)
# wish(name='sunny',msg='good evening....')
# wish(msg='good evening....',name='sunny')
# wish('sunny','good evening....')#Valid
# wish('sunny',msg='good evening....')#Valid
# # wish(name='sunny','good evening....')#Invalid
# # Example : 3 --------> [default arguments]
# def wish(name='radhika'):
# print('Hello',name,'good evening.....')
# wish()
# wish('lilly')
# # Example : 4 --------> [variable length arguments]
# def sum(*n):
# total = 0
# for i in n:
# total = total + i
# print('The sum is:',total)
# sum()
# sum(10)
# sum(10,20)
# sum(10,20,30)
# sum(10,20,30,40)
# # Ex :
# def f1(n1, *s):
# print(n1)
# for i in s:
# print(i)
# f1(10)
# f1(10,20)
# f1(10,20,30)
# f1(10,'A',20,'B',30)
# # Ex :
# def f1(*s,n1):
# for i in s:
# print(i)
# print(n1)
# f1(10,20,30,n1=40)
# # Example :
# def f1(**kwargs):
# for k,v in kwargs.items():
# print(k,'=',v)
# f1(n1=10,n2=20,n3=30)
# f1(rno=101,name='radhika',marks=98,subject='python')
# # CASE STUDY :
# def f(arg1,arg2,arg3=4,arg4=8):
# print(arg1,arg2,arg3,arg4)
# f(3,2)#3 2 4 8
# f(10,20,30,40)#10 20 30 40
# f(25,50,arg4=100)#25 50 4 100
# f(arg4=2,arg1=3,arg2=4)#3 4 4 2
# f()# f() missing 2 required positional arguments: 'arg1' and 'arg2'
# f(4,5,arg2=6)#f() got multiple values for argument 'arg2'
# # f(arg3=10,arg4=20,30,40)#positional argument follows keyword argument
# f(4,5,arg3=5,arg5=6)# f() got an unexpected keyword argument 'arg5'
# def f(*,a,b): # Keyword only argument
# print(a,b)
# # print(type(a),type(b))
# f(a=10,b=20)
# f(b=20,a=10)
# f(10,20) #TypeError: f() takes 0 positional arguments but 2
# def f(a,b,/): # Positional only arguments.
'''
Function vs Module vs Package vs Library:
---------------------------------------------------------------
-->A group of lines with some name is called as a function.
-->A group of functions saved to a file is called as module.
-->A group of modules is nothing but package.
-->A group of packages is nothing but library.
Types of variables:
1.Global variables
2.Local varisbles
1.Global variables:
------------------------
-->If the value of a variable is defined outside a function then such type of variables are called as global variables.
-->Global variables can be accessed inside as well as outside of the function.
-->If we change the value of global variable inside a function then the change will be reflected in outside of the function also.
-->If we declare a variable inside a function with same name as global variable then this local variable will be given preference.
-->If we want to modify the value of global variable inside a function then we should use global keyword.
Ex:
a = 10 #global variables
def f1():
print('f1:',a)
def f2():
print('f2:',a)
f1()
f2()
2.Local Variable:
------------------
-->The variable which are declared inside a function are called as local variable.
-->Local Variable are available only for the function in which we declared it. i.e from outside of function we cant access.
def f1():
a = 10 #local variables
print('f1:',a)
def f2():
print('f2:',a)#NameError: name 'a' is not defined
f1()
f2()
3.Global Keyword:
------------------
-->If we want to modify the value of global variable inside a function then we should use global keyword.
-->To declare global variable inside a function.
-->To make global variable available to the function so that we can perform requirement modifications.
Ex:
a = 10
def f1():
global a
a = 333 #global
print('f1:',a)
def f2():
print('f2:',a)
f1()==>333 f2()==>10
f2()==>333 f1()==>333
Note :
* If the global variable and local variable having same name then we can access global variable inside a
function by using globals() function.
a = 10
def f1():
a = 333
print('f1:',a)#333
print(globals()['a'])#10
f1()
'''
# Example : ---> Global variable.
# a = 10
# def f1():
# print("The f1 value is:",a)
# def f2():
# print("The f2 value is:",a)
# f1()
# f2()
# Example : ---> Local variable.
# def f1():
# a = 10
# print("The f1 value is:",a)
# def f2():
# print("The f2 value is:",a)
# f1()
# f2()
# Example : ---> Global keyword.
# a = 10
# def f1():
# global a
# a = 333
# print("The f1 value is:",a)
# def f2():
# print("The f2 value is:",a)
# f1()
# f2()
# # By using the globals keyword
# a = 10
# def f1():
# global a
# a = 333
# print("The f1 value is:",a)
# print(globals()['a'])
# f1()
'''
RECURSIVE FUCNTION :
--------------------------------
* A function that calls itself is know as recursive function.
Ex:
factorial(3):3*factorial(2)
3*2*factorial(1)
3*2*1*factorial(0)
factorial(n):n*factorial(n-1)
* The main advantages are :
* We can reduce length of the code and improve readability.
* We can solve complex problems easily.
def factorial(n):
if n == 0:
result = 1
else:
result = n*factorial(n-1)
return result
print('Factorial of 4 is:',factorial(4))
print('Factorial of 5 is:',factorial(5))
'''
# Write a program factorial in recursive function
# def factorial(n):
# if n == 0:
# result = 1
# else:
# result = n * factorial(n-1)
# return result
# print('Factorial of 4 is:',factorial(4))
# print('Factorial of 5 is:',factorial(5))
'''
ANONYMOUS FUNCTION :
--------------------------------
* Sometimes we can declare a function without name, such type of nameless functions are called as anonymous funcitons or lambda expressions.
* The main advantage of anonymous function is just for instant use(i.e for one time useage.)
Syn:
lambda argument_list:expression
Note:
By using lambda functions we can write concise code so that readability of the program will be improved
Note:
Lambda function internally returns expression value and we are not required to write retuen statement explicitly.
Some times we can pass function as argument to another function. In such case lambda functions are best choice.
We can use lambda functions very commonly with filter(), map() and reduce() functions bcoz these functions expect function as argument.
'''
# Write a program to create a lambda function to find square of given number.
# Normal func:
# --------------------
# def squareit(n):
# return n*n
# print(squareit(3))
# print(squareit(4))
# # lambda func:
# # --------------------
# s = lambda n:n*n
# print('The square of 3 is:',s(3))
# print('The square of 5 is:',s(5))
# Write a lambda to find sum of 2 given numbers.
# s = lambda a,b : a + b
# print('The sum of 10 and 20 is:',s(10,20))
# print('The sum of 100 and 200 is:',s(100,200)).
# Write a lambda function to find biggest of 2 numbers.
# s = lambda a,b : a if a>b else b
# print('The biggest of 10 and 20 is:',s(10,20))
# print('The biggest of 100 and 200 is:',s(100,200))
# Q.
# add = lambda x,y:x+y
# result = add(3,5)*(lambda x:x**2)(2)
# print(result)#32
# # Q.
# a = {1,1,1,2,2,6,6,6,6}
# b = list(a)
# print(b[2])
# # Q.
# s = 'python'
# for i in range(len(s)):
# print(s)
# s = 'a'
# '''
# 1.filter() function :
# -------------------
# * We can use filter() function to filter values from the given sequence based on some conditions.
# syntax :
# filter(function,sequence)
# * Where function argument is responsible to perform conditional check, sequence can be list or tuple or string.
# 2.map() function :
# ----------------
# * For every element present in the given sequence,apply some functionality and generate new element woith the required modifications.
# For this we should go for map() function.
# syntax :
# map(function,sequence)
# * The function can be applied on each element of sequence and generates new sequence.
# 3. Reduce() function :
# --------------------
# * It reduces sequences of elements into a single element by applying the specified function.
# syntax :
# reduce(function,sequence)
# * Reduce function present in functools module , hence we should import the reduce
# '''
# # Q : W.A.P to filter even numbers from the list by using filter()
# # Without lambda function :
# def is_even(num):
# if num % 2 == 0: # For odd numbers we can use if num%2!=0:
# return True
# else:
# return False
# l = [0,1,2,3,4,5,6,7,8,9,10]
# print(list(filter(is_even , l)))
# # With lambda function :
# l = [0,5,10,15,20,25,30,35,40]
# print(list(filter(lambda num:num%2==0,l)))
# print(list(filter(lambda num:num%2!=0,l)))
# # -------------------------------------------- Map function --------------------------------------------
# # Q : W.A.P to print every element present in the list perform double and generates new list of doubles.
# # Without lambda function
# l = [1,2,3,4,5]
# def doubleit(n):
# return 2*n
# print(list(map(doubleit,l)))
# # With lambda function
# l = [1,2,3,4,5]
# print(list(map(lambda x:2*x , l)))
# print(list(map(lambda x:x*x , l)))
# l1 = [1,2,3,4,5]
# l2 = [6,7,8,9,10]
# print(list(map(lambda x,y : x*y , l1,l2)))
# # -----------------------------------------------------Reduce function -----------------------------------------
# # EXAMPLE :
# from functools import reduce
# l = [10,20,30,40,50]
# result = reduce(lambda x,y : x+y , l)
# print(result)
# # Q. W.A.P to print sum of first 100 numbers.
# from functools import reduce
# result = reduce(lambda x,y:x+y,range(1,101))
# print(result)
# # Nested Functions:
# # --------------------------
# def f1():
# def inner(a,b):
# print('The sum is:',a+b)
# print('The product is:',a*b)
# print()
# inner(10,20)
# inner(20,30)
# inner(30,40)
# f1()
# # Ex:
# def outer():
# print('Outer function started')
# def inner():
# print('Inner function started')
# print('Outer function returning inner function')
# return inner
# f1 = outer()
# f1()
# # Note:
# f1 = outer() #Function call
# f1 = outer #Function aliasing
'''
Function Decorators :
---------------------
* Decorators is a function which can take a function as a argument and extends its functionality.
input function ----> Decorator function --------> output with extended function.
* The main objective of decorator function is we can extend the functionality of existing functions without modified that function.
* Decorators helps to make our code shorter. This concept is very helpful while developing web applications with Django.
Example :
def wish(name):
print("Hello",name,"good evening.......")
This function can always print same output for any name.
But we want to modify this function to provide different message if name is 'radhika'.
We can do this without touching wish() function by using decorator.
****Decoartor chaining*********
* We can define multiple decorators for the same function and all these decorators will perform decorator chaining.
Ex:
@decor1
@decor
def num():
-->For num() function we are applying 2-decorators. First inner decorator will work and then outer decorator.
'''
# Example :
def decor(func):
def inner(name):
if name == 'radhika':
print("Hello",name,"very very good evening......")
else:
func(name)
return inner
@decor
def wish(name):
print("Hello",name,"good evening.......")
wish('naresh')
wish('radhika')
wish('mahesh')
# How to call same function without decorator
def smart_division(func):
def inner(a,b):
print("We are dividing",a,'with',b)
if b == 0:
print("We can't divide with zero")
else:
return func(a,b)
return inner
@smart_division
def division(a,b):
return a/b
print(division(20,2))
print(division(20,0))
# Decorator chaining example :
def decor(func):
def inner():
x = func()
return x*x
return inner
def decor1(func):
def inner():
x = func()
return 2*x
return inner
@decor1
@decor
def num():
return 10
print(num())
'''
Generators in python :
----------------------
* Generators is a function which is responsible to generate a sequence of values.
* We can write generator function just like ordinary function,but it uses yield keyword to return values.
yield---------->Generator----------------->A sequence of values.
Ex:
def mygen():
yield 'A'
yield 'B'
yield 'C'
g = mygen()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
Advantages of generator functions:
----------------------------------------------------
-->When compared with class level iterations, generators are very easy to use.
-->Improves memory utilization and performance.
-->Generators are best suitable for reading data from large number of large files.
-->Memory utilization, bcoz we are not required to store all values at a time.
'''
# Example :
def mygen():
yield 'A'
yield 'B'
yield 'C'
g = mygen()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
# Generate a sequence of values from 5 to 1
def countdown(num):
print('Started countdown')
while num > 0:
yield num
num = num - 1
values = countdown(5)
for x in values:
print(x)
# To generate first n numbers
def first(num):
i = 1
while i<= num:
yield i
i += 1
values = first(10)
for x in values:
print(x)
# # we can convert generator into a list
values = first(5)
print(list(values))
# To generate to fibonacci number : ------------>0,1,1,2,3,5,8,13,21,.....................
def fib():
a,b = 0,1
while True:
yield a
a,b = b,a+b
for x in fib():
if x > 100:
break
print(x)