More Python - Functions and Modules
More Python - Functions and Modules
by
Kaustubh Vaghmare
(IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in
1 of 28
Friday 25 July 2014 04:12 PM
Functions
Blocks of code that perform a specific task.
In Python, a function is defined using the "def" keyword.
We have already seen examples of functions.
float(), dict(), list(), len() etc. math - sqrt(), floor(), ceil(), radians(), sin() open(), type() etc.
2 of 28
Friday 25 July 2014 04:12 PM
A Simple Function
In [13]: def myfun(): print "Hello World!" print "Nice to see you."
print "Outside the function."
Outside the function.
Pay attention to how the statements indented one level up are part of the function while the statement indented at the same level is not a part of the function.
In [14]: myfun() # This is how you call our function.
Hello World! Nice to see you.
3 of 28
Friday 25 July 2014 04:12 PM
Function With One Argument
In [15]: def myfun(a): print "Inside MyFun!" print a
In [16]: myfun() # WILL GIVE ERROR.
---------------------------------------------------------------
------------
TypeError
Traceback (most recen
t call last)
in ()
----> 1 myfun() # WILL GIVE ERROR.
TypeError: myfun() takes exactly 1 argument (0 given)
As per function definition, one argument / input is needed. An attempt to call the function with none gives an error. EVEN supplying two arguments is wrong.
4 of 28
Friday 25 July 2014 04:12 PM
In [17]: myfun("An Input")
Inside MyFun! An Input
REMEMBER
Python is a dynamically typed language. The true strength of this lies in the fact that you can also call the above function with a float or integer or list input!
In [18]: myfun(5) Inside MyFun! 5
In [19]: myfun( [1,2,3] ) Inside MyFun! [1, 2, 3]
5 of 28
Friday 25 July 2014 04:12 PM
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.