Python tutorial- Function


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:
def 
                        your code here…
                        return[value]
Example:
>>>def hello():
        print 'Hello'
        return
>>hello()
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):
            result=a+b
            return result
 
>>> mysum(10,20)
30
>>> 
These parameters can have default values.
 >>> def mysum(a=10,b=20):
            result=a+b
            return result
 
>>> mysum()
30
>>> 
 
You also can supply many values as you want. Please consider the following function.
 
>>> def multi_values_param(*params):
            print params
            return
           
>>> 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
            return
 
>>> multi_values_param(1,2,3,4,5)
 
Traceback (most recent call last):
  File "<pyshell#92>", line 1, in <module>
    multi_values_param(1,2,3,4,5)
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}
>>> 


Comments




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.