FUNCTIONS
What Good are Functions?
You might have considered the situation where you would like to reuse a piece of code, just with a few different values. Instead of rewriting the whole code, it’s much cleaner to define a function, which can then be used repeatedly.
Function :
Functions are defined with three components:
- The header, which includes the
def
keyword, the name of the function, and any parameters the function requires. Here’s an example:def hello_world(): # There are no parameters - An optional comment that explains what the function does."""Prints 'Hello World!' to the console."""
- The body, which describes the procedures the function carries out. The body is indented, just like conditional statements.print "Hello World!"
Here’s the full function pieced together:
def hello_world(): """Prints 'Hello World!' to the console.""" print "Hello World!"i.edef mywebsite():"""Prints 'tushargahora.blogspot.com' to the console.""" print "tushargahora.blogspot.com"Call and Response
After defining a function, it must be called to be implemented. In the above para,mywebsite()
in the last line told the program to look for the function called mywebsite and execute the code inside it.Parameters and Arguments
Let’s take another look at the definition of the functionsquare
:
def square(n):Here,n
is a parameter ofsquare
. A parameter is a variable that is an input to a function. It says, “Later, whensquare
is used, you’ll be able to input any value you want, but for now we’ll call that future value n.” A function can have any number of parameters.The values of the parameters passed into a function are known as the arguments. Recall in the previous example, we called:py square(10)
Here, the functionsquare
was called with the parametern
set to the argument10
.Typically, when you call a function, you should pass in the same number of arguments as there are parameters.To summarize:
- When defining a function, placeholder variables are called parameters.
- When using, or calling, a function, inputs into the function are called arguments.
Functions Calling Functions
We’ve seen functions that can print text or do simple arithmetic, but functions can be much more powerful than that. For example, a function can call another function:
def fun_one(n): return n * 5 def fun_two(m): return fun_one(m) + 7Generic Imports
Did you see that? Python said:NameError: name 'sqrt' is not defined.
Python doesn’t know what square roots are—yet.There is a Python module namedmath
that includes a number of useful variables and functions, andsqrt()
is one of those functions. In order to accessmath
, all you need is theimport
keyword. When you simply import a module this way, it’s called a generic import.Function Imports
Python knows how to take the square root of a number.However, we only really needed thesqrt
function, and it can be frustrating to have to keep typingmath.sqrt()
.It’s possible to import only certain variables or functions from a given module. Pulling in just a single function from a module is called a function import, and it’s done with thefrom
keyword:
from module import functionNow you can just typesqrt()
to get the square root of a number—no moremath.sqrt()
!Universal Imports
Great! We’ve found a way to handpick the variables and functions we want from modules.What if we still want all of the variables and functions in a module but don’t want to have to constantly typemath.
?Universal import can handle this for you. The syntax for this is:
from module import *On Beyond Strings
Now that you understand what functions are and how to import modules, let’s look at some of the functions that are built in to Python (no modules required!).You already know about some of the built-in functions we’ve used with strings, such as.upper()
,.lower()
,str()
, andlen()
. These are great for doing work with strings, but what about something a little more analytic?max()
Themax()
function takes any number of arguments and returns the largest one. (“Largest” can have odd definitions here, so it’s best to usemax()
on integers and floats, where the results are straightforward, and not on other objects, like strings.)For example,max(1,2,3)
will return3
(the largest number in the set of arguments).min()
min()
then returns the smallest of a given series of arguments.abs()
Theabs()
function returns the absolute value of the number it takes as an argument—that is, that number’s distance from0
on an imagined number line. For instance,3
and-3
both have the same absolute value:3
. Theabs()
function always returns a positive value, and unlikemax()
andmin()
, it only takes a single number.type()
Finally, thetype()
function returns the type of the data it receives as an argument. If you ask Python to do the following:
print type(42) print type(4.2) print type('Blogger's Hub')Python will output:
<type 'int'> <type 'float'> <type 'str'>
No comments: