Function Guide
28 JANUARY 2020
Python Function Guide with Examples
Introduction to Functions in Python
A function allows you to define a reusable block of code that can be executed many times within your program.
Functions allow you to create more modular and DRY solutions to complex problems.
While Python already provides many built-in functions such as print()
and len()
, you can also define your own functions to use within your projects.
One of the great advantages of using functions in your code is that it reduces the overall number of lines of code in your project.
Syntax
In Python, a function definition has the following features:
The keyword
def
a function name
paranthesis’()’, and within paranthesis input parameters,although the input parameters are optional.
a colon ’:’
some block of code to execute
a return statement (optional)
Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code both more readable, makes for easier debugging, and limits typing errors.
Functions in Python are created using the def
keyword, followed by a function name and function parameters inside parentheses.
A function always returns a value,The return
keyword is used by the function to return a value, if you don’t want to return any value, the default value None
will returned.
The function name is used to call the function, passing the needed parameters inside parentheses.
You can define default values for the parameters, that way Python will interpretate that the value of that parameter is the default one if none is given.
You can pass the parameters in the order you want, using the name of the parameter.
However, it is not possible to pass a keyword argument before a non-keyword one
Functions are also Objects, so you can assign them to a variable, and use that variable like a function.
Notes
If a function definition includes parameters, you must provide the same number of parameters when you call the function.
The block of code that the function will run includes all statements indented within the function.
Variables defined within a function only exist within the scope of that function.
Python interprets the function block only when the function is called and not when the function is defined.So even if the function definition block contains some sort of error, the python interpreter will point that out only when the function is called.
Now let's look at some specific functions with examples.
max() function
max()
is a built-in function in Python 3. It returns the largest item in an iterable or the largest of two or more arguments.
Arguments
This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it. Syntax: max(iterable, *iterables[,key, default]) max(arg1, arg2, *args[, key])
Valid Arguments:
Invalid Arguments:
Return Value
The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. If the iterable is empty and default is not provided, a ValueError
is raised.
Code Sample
min() function
min()
is a built-in function in Python 3. It returns the smallest item in an iterable or the smallest of two or more arguments.
Arguments
This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.
Valid Arguments:
Invalid Arguments:
Return Value
The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. If the iterable is empty and default is not provided, a ValueError is raised.
Code Sample
divmod()
is a built-in function in Python 3, which returns the quotient and remainder when dividing the number a
by the number b
. It takes two numbers as arguments a
& b
. The argument can’t be a complex number.
Argument
It takes two arguments a
& b
- an integer, or a decimal number.It can’t be a complex number.
Return Value
The return value will be the pair of positive numbers consisting of quotient and remainder obtained by dividing a
by b
. In case of mixed operand types, rules for binary arithmetic operators will be applied.
For Integer number arguments, return value will be same as (a // b, a % b)
.
For Decimal number arguments, return value will be same as (q, a % b)
, where q
is usually math.floor(a / b) but may be 1 less than that.
Code Sample
Hex(x) function
hex(x)
is a built-in function in Python 3 to convert an integer number to a lowercase hexadecimal string prefixed with “0x”.
Argument
This function takes one argument, x
, that should be of integer type.
Return
This function returns a lowercase hexadecimal string prefixed with “0x”.
Example
len() function
len()
is a built-in function in Python 3. This method returns the length (the number of items) of an object. It takes one argument x
.
Arguments
It takes one argument, x
. This argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
Return Value
This function returns the number of elements in the argument which is passed to the len()
function.
Code Sample
Ord function
ord()
is a built-in function in Python 3, to convert the string representing one Unicode character into integer representing the Unicode code of the character.
Examples:
chr function
chr()
is a built-in function in Python 3, to convert the integer representing the Unicode code into a string representing a corresponding character.
Examples:
One thing is to be noted that, if the integer value passed to chr()
is out of range then, a ValueError will be raised.
input() functions
Many a time, in a program we need some input from the user. Taking inputs from the user makes the program feel interactive. In Python 3, to take input from the user we have a function input()
. If the input function is called, the program flow will be stopped until the user has given an input and has ended the input with the return key. Let’s see some examples:
When we just want to take the input:
inp = input()
To give a prompt with a message:
prompt
with
message = input(’‘)
3. When we want to take an integer input:
If you enter a non integer value then Python will throw an error ValueError
. So whenever you use this, please make sure that you catch it too. Otherwise, your program will stop unexpectedly after the prompt.
4. When we want a string input:
Though, inputs are stored by default as a string. Using the str()
function makes it clear to the code-reader that the input is going to be a ‘string’. It is a good practice to mention what type of input will be taken beforehand.
How to call a function in Python
A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.
The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:
Reference : https://www.freecodecamp.org/news/python-function-guide-with-examples/
Last updated