xxxxxxxxxx
# if args is not passed it return message
# "Hey you didn't pass the arguements"
def ech(nums,*args):
if args:
return [i ** nums for i in args] # list comprehension
else:
return "Hey you didn't pass args"
print(ech(3,4,3,2,1))
xxxxxxxxxx
>>> def argsKwargs(*args, **kwargs):
print(args)
print(kwargs)
>>> argsKwargs('1', 1, 'slgotting.com', upvote='yes', is_true=True, test=1, sufficient_example=True)
('1', 1, 'slgotting.com')
{'upvote': 'yes', 'is_true': True, 'test': 1, 'sufficient_example': True}
xxxxxxxxxx
############################# ARGS ###########################################
def my_function(*kids):
print(kids)
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
>>>('Emil', 'Tobias', 'Linus')
The youngest child is Linus
############################# KWARGS #########################################
def my_function(**kid):
print(kid)
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
>>>{'fname': 'Tobias', 'lname': 'Refsnes'}
His last name is Refsnes
xxxxxxxxxx
def add(*args):
total = 0
for i in args:
total += i
return total
print(add(5,5,10))
xxxxxxxxxx
# *args is a Variable Length Argument of type Tuple,
# which takes any number of parameters, including 0 number of arguments as well.
def variableLengthArguments(*args):
print (sum(args))
variableLengthArguments() # Output: 0
variableLengthArguments(10) # Output: 10
variableLengthArguments(10, 20) # Output: 30
variableLengthArguments(10, 20, 30, 50, 90) # Output: 200
xxxxxxxxxx
def mul(*args): # args as argument
multiply = 1
for i in args:
multiply *= i
return multiply
lst = [4,4,4,4]
tpl = (4,4,4,4)
print(mul(*lst)) # list unpacking
print(mul(*tpl)) # tuple unpacking
xxxxxxxxxx
def func(*args):
x = [] # emplty list
for i in args:
i = i * 2
x.append(i)
y = tuple(x) # converting back list into tuple
return y
tpl = (2,3,4,5)
print(func(*tpl))
xxxxxxxxxx
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
print 'count:', len(sys.argv)
print 'list:', str(sys.argv)
xxxxxxxxxx
def display(a,b,c):
print("arg1:", a)
print("arg2:", b)
print("arg3:", c)
lst = [2,3]
display(1,*lst)
xxxxxxxxxx
# normal parameters with *args
def mul(a,b,*args): # a,b are normal paremeters
multiply = 1
for i in args:
multiply *= i
return multiply
print(mul(3,5,6,7,8)) # 3 and 5 are being passed as a argument but 6,7,8 are args