Python tutorial- Function


By writing your code in functions, you simply benefit at least two important things: breaking down a large job to smaller jobs that are easy to track, and reusable code. To define a function in Python, you must use def keyword. The formula can be written as shown below:
                        your code here…
>>>def hello():
        print 'Hello'
Note: if your function doesn’t return a value, you just write return and leave the value blank.
A function can have a parameter or more.
>>> def mysum(a,b):
            return result
>>> mysum(10,20)
These parameters can have default values.
 >>> def mysum(a=10,b=20):
            return result
>>> mysum()
You also can supply many values as you want. Please consider the following function.
>>> def multi_values_param(*params):
            print params
>>> multi_values_param('Dara','Channa','Pagan')
('Dara', 'Channa', 'Pagan')
Note: *params parameter will be printed in a tuple form. If you want to print it in a dictionary form, you need to add one more star (*).
>>> def multi_values_param(**params):
            print params
>>> multi_values_param(1,2,3,4,5)
Traceback (most recent call last):
  File "<pyshell#92>", line 1, in <module>
TypeError: multi_values_param() takes exactly 0 arguments (5 given)
A dictionary form is a form of {key,value}. If you supply only values to the function, the error will be raised. Therefore, you need to supply both keys and values with equal mark (=).
>>> multi_values_param(a=1,b=2,c=3,d=4,e=5)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.