return func1
: reference to func1
.return func1()
: results of evaluating func()
.If a function doesn't return any value, it returns None
.
# without arguments
def func_name():
pass
# with arguments
def func_name(<args>):
pass
# return
def func_name(<args>):
return <some_thing>
# call a function
func_name(<args>)
def sum_and_div(num1, num2):
sum_nums = num1 + num2
div_nums = num1 / num2
return sum_nums, div_nums # multiple returns
sum, div = sum_and_div(18, 9)
print(sum, div)
# output
27 2.0
args
and *kwargs
)The *args
will give you all function parameters as a tuple: (ref)
def foo(*args):
print(args)
for a in args:
print(a)
foo(1)
foo(2, 3, 4)
# output
(1,)
1
(2, 3, 4)
2
3
4
def foo(rarg1, rarg2):
print(rarg1, rarg2)
lst = [1, 2]
foo(*lst)
tpl = (3, 4)
foo(*tpl)
# output
1 2
3 4
If you wanna use "keywords arguments", use **args
:
def kwfunc(**kwargs):
print(type(kwargs))
print(kwargs)
kwfunc()
kwfunc(kw1="thi", kw2="dinh")
# output
<class 'dict'>
{}
<class 'dict'>
{'kw1': 'thi', 'kw2': 'dinh'}
Use a dictionary as an input,
def kwfunc(**kwargs): # must have **
print(kwargs)
kwargs = {'kw1': "thi", 'kw2': "dinh"}
kwfunc(**kwargs) # must have **
# output
{'kw1': 'thi', 'kw2': 'dinh'}
def kwfunc(kw1="john", kw2="doe"):
print(kw1, kw2)
kwargs = {'kw1': "thi", 'kw2': "dinh"}
kwfunc()
kwfunc(kwargs) # goes to kw1
kwfunc(**kwargs) # goes to both kw1 & kw2
# output
john doe
{'kw1': 'thi', 'kw2': 'dinh'} doe
thi dinh
Coupling rargs
, *args
and **kwargs
: