Python Functions
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1422003450156-2'); });
Python Functions
❮ Previous
Next ❯
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def
keyword:
Example
def my_function():
print("Hello from a function")Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Run example »
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname).
When the function is called, we pass along a first name,
which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")Run example »
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1493883843099-0'); });
Default Parameter Value
The following example shows how to use a default paramter value.
If we call the function without parameter, it uses the default value:
Example
def my_function(country = "Norway"):
print("I am from " +
country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")Run example »
Return Values
To let a function return a value, use the return
statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))Run example »
Lambda Functions
In python, the keyword lambda is used to create what is known as anonymous functions. These are essentially functions with no pre-defined name. They are good for constructing adaptable functions, and thus good for event handling.
Example
An anonymous function that returns the double value of i:
myfunc = lambda i: i*2
print(myfunc(2))
Run example »
Lambda defined functions can have more than one defined input, as shown here:
Example
myfunc = lambda x,y: x*y
print(myfunc(3,6))
Run example »
The power of lambda is better shown when you generate anonymous functions at run-time, as shown in the following example.
Example
def myfunc(n):
return lambda i: i*n
doubler = myfunc(2)
tripler = myfunc(3)
val = 11
print("Doubled: " + str(doubler(val)) + ". Tripled: " + str(tripler(val)))
Run example »
Here we see the defined function, myfunc, which creates an anonymous function that
multiplies variable i with variable n.
We then create two variables doubler and tripler, which are assigned to the result of
myfunc passing in 2 and 3 respectively. They are assigned to the generated lambda functions.
❮ Previous
Next ❯