Python Functions Tutorial

Function makes the code more organized, its basically a piece of reusable code block. Python has a lot of built-in functions such as print(), str(), zip(), etc. You can also create your functions known as user-defined functions.

How to define a function

A function definition starts with the keyword def followed by the function name and then parameters. The code block for a function starts after the colon (:). If first line in the code block is a string then it is stored as part of the function and is called a docstring. The function may or may not return a value.
>>> def addNumbers (parm1, parm2):
 "This function adds two numbers"
 result = parm1 + parm2
 return result

>>> print(addNumbers(2, 3))
5

Global variable versus Local variable and parameter passing by reference

In python parameters are passed by reference so if you pass a parameter to a function and then change its value inside the function you can see the changes outside the function. But if you assign a value to a parameter inside a function then it creates a new variable which is local to the function and not the same variable that's defined outside the function so the value of that variable cannot change. So if you pass a string, since strings are immutable there is no way you can get the changes outside the function whereas if you pass a list and update then the original value is updated. Every function in python creates a namespace and variables defined within are scoped within that namespace. Here are a few examples to demonstrate the scoping and parameter passing by reference.
>>> def myFunction(name):
 name = "John"
 print(name);
 return

>>> name = "Jake"
>>> myFunction(name)
John
>>> print(name)
Jake
>>> def myFunction(names):
 names = ["John","Sam"]
 print(names);
 return

>>> myList = ["Jake","Ed"]
>>> myFunction(myList)
['John', 'Sam']
>>> myList
['Jake', 'Ed']
>>> def myFunction(names):
 names.append("Just Added")
 print(names);
 return

>>> myList = ["Jake","Ed"]
>>> myFunction(myList)
['Jake', 'Ed', 'Just Added']
>>> myList
['Jake', 'Ed', 'Just Added']

Keyword parameters and default values

If you just send the name of the parameters when calling the function then you don't have to pass then in their respective positions.
>>> def myHello(greeting, name):
 print(greeting + " " + name)
 return

>>> myHello("hello", "world!")
hello world!
>>> myHello(greeting="hello", name="world!")
hello world!
>>> myHello(name="world!", greeting="hello")
hello world!

If there is default value for a parameter then it becomes optional to send.
>>> def myHello(name, greeting="hello"):
 print(greeting + " " + name)
 return

>>> myHello("world!","hi")
hi world!
>>> myHello("world!")
hello world!
>>> myHello(name="world!")
hello world!
>>> myHello(name="world!",greeting="hi")
hi world!

Variable length parameter collection

If you specify an argument with a single asterisk(*) then they are all collect in a tuple and if you specify an argument with double asterisk(**) then it creates a dictionary with the name and value pairs.
>>> def myFunction(arg1, arg2, *parms):
 print(arg1)
 print(arg2)
 print(parms)
 for x in parms:
  print(x)
 return

>>> myFunction("hello","hi","a","b","c")
hello
hi
('a', 'b', 'c')
a
b
c
>>> def myFunction(arg1, arg2, **parms):
 print(arg1)
 print(arg2)
 print(parms)
 for key,value in parms.items():
  print(key + " --> " + value)
 return

>>> myFunction("hello","hi",a="1",b="2",c="2")
hello
hi
{'a': '1', 'c': '2', 'b': '2'}
a --> 1
c --> 2
b --> 2
>>> def myFunction(arg1, arg2, *parms, **args):
 print(arg1)
 print(arg2)
 print(parms)
 for x in parms:
  print(x)
 print(args)
 for key,value in args.items():
  print(key + " --> " + value)
 return

>>> myFunction("hello","hi",1,2,3,4,a="1",b="2",c="2")
hello
hi
(1, 2, 3, 4)
1
2
3
4
{'a': '1', 'c': '2', 'b': '2'}
a --> 1
c --> 2
b --> 2

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.