My Coding > Programming language > Python > Python functions calls

Python functions calls

Function can be declared by command def with function body following this definition. The most important is to understand, how you can send and receive data to the function and obrain results

returning result from function in Python


def func(): # function definition with or without parameters
  # executable body
  return() # function return required parameters or ‘None’ and stop execution
           # return is not obligatory

function calls with parameters

There are 4 ways to send parameters to function:


def func( a, b=3 ): # function definition
  print( "→", a+b)
  return()
func( 10, 20 )      # a=10, b=20; →30
func( 10 )          # a=10, b=30; →40
func( a=10 )        # a=10, b=30; →40
func( a=10, b=20 )  # a=10, b=20; →30
func( b=20, a=10 )  # a=10, b=20; →30
lst=[1,2]
func( *lst )        # = func( lst[0], lst[1] ); a=1, b=2; →3
args = {'a':2, 'b':4}
func( **args )      # = func( key1=args[key1], key2=args[key2])
                    # func( a=2, b=4) ; a=2, b=4; →6

Function parameters receiving

There are 4 ways to receive parameters in the Python function

positional parameters


def print_all(a,b): 
  print("positional a =",a)
  print("positional b =",b)
print_all( 1, 2 )
#positional a = 1
#positional b = 2

positional parameters with defailt values


def print_all(a,b=10):
  print("positional a =",a)
  print("positional b =",b)
print_all( 1 )
#positional a = 1
#positional b = 10

list of parameters


def print_all(a,b, *args):
  print("positional a =",a)
  print("positional b =",b)
  for arg in args:
    print( "additional: ", arg )
lst=[3,4,5]
print_all( 1,2, *lst )
#positional a = 1
#positional b = 2
#additional:  3
#additional:  4
#additional:  5

keyworded parameters


def print_all(a,b, **kwargs):
  print("positional a= ",a)
  print("positional b= ",b)
  for key in kwargs:
    print( "additional: ", key, kwargs[key] )
kwd={'c':3, 'd':4, 'e':5}
print_all( 1,2, **kwd )
#positional a=  1
#positional b=  2
#additional:  c 3
#additional:  d 4
#additional:  e 5

All allowed parameters

Full allowed combination of parameters


def print_all(a,b, *args, c, d, **kwargs): # a b c & d can has default values


Published: 2021-09-17 21:23:20
Updated: 2023-05-09 01:29:01

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.