Python User Defined Functions

  • Use keyword def to create the function followed by the name of the function and the parenthesized list of parameters if any.
  • The first statement of the function body can be optionally be a string literal (docstring). It’s good practice to include docstrings in code that you write.
  • The actual parameters (arguments) to a function are passed when the function is called.
  • The return statement returns with a value from a function and return without an expression argument returns None.
  • We can create functions with default argument values, keyword arguments, arbitrary argument lists
  • In Python, arguments are passed using call by value, where the value is always an object reference, not the value of the object
  • The value of the function name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which can then also be used as a function.

Simple User Defined Function

>>> def display():
...     """ Prints Hello World """
...     print("Hello World from function")
...
>>> display()
Hello World from function
>>> type(display())
Hello World from function
<class 'NoneType'>

Let us define more functions by passing a parameter

>>> def displayName(name):
...     print("My Name is: "+ name)
...
>>> displayName("Girish")
My Name is: Girish
>>>

>>> def fib(n): # Write Fibonacci Series up to n
...     """ Print a Fibonacci Series up to n."""
...     a, b = 0, 1
...     while a < n:
...             print(a, end=' ')
...             a, b = b, a+b
...     print()

>>> fib(5)
0 1 1 2 3
>>> fib
<function fib at 0x036B0D68>
>>> f = fib
>>> f(50)
0 1 1 2 3 5 8 13 21 34
>>> fib(0)
>>> print(fib(0))
None
>>> days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
>>> def displayList(listName):
...     for x in listName:
...             print(x)
...
>>> displayList(days)
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
>>>

>>> def fibList(n):
...     """ Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...             result.append(a)
...             a, b = b, a+b
...     return result
...
>>> fibList(5)
[0, 1, 1, 2, 3]
>>> fl = fibList
>>> fl(5)
[0, 1, 1, 2, 3]

We can create functions with default argument values, keyword arguments, arbitrary argument lists

Default Argument Values

>>> def course_instructor(name="Girish"):
...     print("Our Course Instructor Name is: " + name)
...
>>> course_instructor()
Our Course Instructor Name is: Girish
>>> course_instructor("Sanjay")
Our Course Instructor Name is: Sanjay

>>> def printNumbers(n=10):
...     for i in range(n):
...             print(i)
...
>>> printNumbers()
0
1
2
3
4
5
6
7
8
9
>>> printNumbers(5)
0
1
2
3
4

>>> def myfunc(a, myList=[]):
...     myList.append(a)
...     return myList
...
>>> myfunc(1)
[1]
>>> myfunc(2)
[1, 2]
>>> myfunc(3)
[1, 2, 3]

>>> def myfunc(a, myList = None):
...     if myList is None:
...             myList =[]
...     myList.append(a)
...     return myList
...
>>> myfunc(4)
[4]
>>> myfunc(3)
[3]

>>> myList = []
>>> myList
[]
>>> myList.append(2)
>>> myList
[2]
>>> myList.append(3)
>>> myList
[2, 3]
>>> myList.append(10)
>>> myList
[2, 3, 10]

>>> def myfunc(n, myList = []):
...     myList.append(n)
...     return myList
...
>>> myfunc(10)
[10]

Functions with keyword arguments

>>> def course(name, trainer="Girish", mode ="Online", type="short term"):
...     print("Course Name: "+ name)
...     print("Trainer Name: "+ trainer)
...     print("Training Mode: "+ mode)
...     print("Training Type: "+ type)
...
>>> course("Python")
Course Name: Python
Trainer Name: Girish
Training Mode: Online
Training Type: short term

>>> course("Python","Sanjay")
Course Name: Python
Trainer Name: Sanjay
Training Mode: Online
Training Type: short term

>>> course(name="Python",trainer="Sanjay")
Course Name: Python
Trainer Name: Sanjay
Training Mode: Online
Training Type: short term

>>> course(name="Python",type="Classroom")
Course Name: Python
Trainer Name: Girish
Training Mode: Online
Training Type: Classroom

Functions with arbitrary argument lists

  • *name receives a tuple containing the positional arguments beyond the formal parameter list.
  • **name receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter.
>>> def courseupdated(course,*feedback,**details):
...     print("Course Name: "+ course)
...     for arg in feedback:
...             print(arg)
...     print("*" * 40)
...     for kw in details:
...             print(kw, ":", details[kw])
...

>>> courseupdated("Python","Girish is an excellent Python Trainer", "Girish is awesome", Appreciation = "Top Class Trainer", Knowledge= "Extraordinary", Remarks="Commendable")
Course Name: Python
Girish is an excellent Python Trainer
Girish is awesome
****************************************
Appreciation : Top Class Trainer
Knowledge : Extraordinary
Remarks : Commendable

>>> def concat(*args, sep="###"):
...     return sep.join(args)
...
>>> concat("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
'Sunday###Monday###Tuesday###Wednesday###Thursday###Friday###Saturday'
>>> def concat(*args, sep="--"):
...     return sep.join(args)
...
>>> concat("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
'Sunday--Monday--Tuesday--Wednesday--Thursday--Friday--Saturday'

>>> list(range(2,6))
[2, 3, 4, 5]
>>> args = [1,10]
>>> list(range(*args))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

References

  • https://docs.python.org/3/tutorial/controlflow.html#defining-functions

Learn more about Built in Functions in Python in our upcoming Blog Articles.

Happy Learning!