+ 1

Defining function

Normally in defining function we need to pass arguments as much as we want to operate on values later. e.g. ----------- def add(x,y): c=x+y print(c) add(4,5) ---------- But what if i want to use less or more values than passed arguments. e.g. ---------- def add(x,y): c=x+y print(c) add(4,5,6) ----------- This creates an error. What should I do if such a situation occurs

16th Mar 2019, 5:25 AM
Manpreet Kaur
Manpreet Kaur - avatar
5 Réponses
+ 10
You can also do it this way def add(*args): return sum(n for n in args) print(add(1, 2)) # 3 print(add(1, 2, 3)) # 6
16th Mar 2019, 6:33 AM
David Ashton
David Ashton - avatar
+ 9
def add(x, y, *z): sum = x+y for arg in z: sum += arg return sum print(add(1, 2)) # 3 print(add(1, 2, 3)) # 6
16th Mar 2019, 5:53 AM
Anna
Anna - avatar
+ 4
You have take only two argument In parenthesis. Your program does not know the role of 6. coz you define only 2 variable. def add(x,y) c = x+y print(c) add(4,5) Where x = 4 y = 5.
16th Mar 2019, 5:41 AM
Rishabh Singh
Rishabh Singh - avatar
+ 3
Rishabh Singh 🔛✴ thats inside the for loop, so arg will work inside the loop, no need to assign it.
16th Mar 2019, 6:01 AM
Abdul S Ansari
Abdul S Ansari - avatar
+ 2
Anna arg is not define.
16th Mar 2019, 5:55 AM
Rishabh Singh
Rishabh Singh - avatar