+ 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
5 Antworten
+ 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
+ 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
+ 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.
+ 3
Rishabh Singh 🔛✴ thats inside the for loop, so arg will work inside the loop, no need to assign it.
+ 2
Anna arg is not define.