# *args
def function1(*args):
return sum(args)
print(function1(1,4,5))
# *args + loop
def function1(*args):
total = 0
for i in args:
total += i
return total
print(function1(1,2,3))
results
#**kwargs
def function2(**names):
print("My name is " + names["fname"])
print("My last name is " + names["lname"])
print("My full name: " + names["lname"], names["fname"])
function2(fname = "Agnieszka", lname = "Szczep")
#def const value then change it
def function3(music = "Rock"):
print("I love " + music + " music")
function3()
function3("Hip-hop")
function3("Trance")
#math recursion model
def function4(k):
if(k > 0):
result = k + function4(k - 1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
function4(4)
Function is a dedicated block of code, which only runs when it is called. It is also an essential element of the DRY (Don’t Repeat Yourself) methodology, i.e. where a functionality will be used many times, we can use the function. In Python a function is defined using the def keyword:
*args collects any number of positional arguments and packs them into a tuple. **kwargs collects named arguments (keyword arguments) into a dictionary (dict).
def function1(*args):
return sum(args)
print(function1(1,4,5))
# *args + loop
def function1(*args):
total = 0
for i in args:
total += i
return total
print(function1(1,2,3))
results
#**kwargs
def function2(**names):
print("My name is " + names["fname"])
print("My last name is " + names["lname"])
print("My full name: " + names["lname"], names["fname"])
function2(fname = "Agnieszka", lname = "Szczep")
result
5 example – def const value then change it
def function3(music = "Rock"):
print("I love " + music + " music")
function3()
function3("Hip-hop")
function3("Trance")
result
7 example – math recursion model
def function4(k):
if(k > 0):
result = k + function4(k - 1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
function4(4)