0% found this document useful (0 votes)
2 views7 pages

Functions in Python

The document explains the concept of functions in Python, detailing their purpose in organizing code into manageable tasks. It covers the advantages of using functions, types of functions (built-in, modules, user-defined), and the structure of user-defined functions including parameters and arguments. Additionally, it discusses the scope of variables, distinguishing between global and local scopes.

Uploaded by

singh.shiva1502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Functions in Python

The document explains the concept of functions in Python, detailing their purpose in organizing code into manageable tasks. It covers the advantages of using functions, types of functions (built-in, modules, user-defined), and the structure of user-defined functions including parameters and arguments. Additionally, it discusses the scope of variables, distinguishing between global and local scopes.

Uploaded by

singh.shiva1502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

FUNCTIONS IN PYTHON

A function is a group of statements that exists within a program for the purpose of performing a specific task.
Instead of writing a large program as one long sequence of instructions, it can be written as several small
functions, each performing a specific part of the task. They constitute line of code(s) that are executed
sequentially from top to bottom by Python interpreter.

It is simply a group of statements under any name, i.e., function name, and can be invoked (called) from
another part of the program. Consider an example of School Management Software which constitutes
various tasks like registering students, fee collection, issuing books from library, TC (transfer certificate)
generation, result declaration, etc. In such cases, we have to create different functions for each task to
manage software development.

Advantages of Functions:

1.​ Program handling becomes easier: Only a small part of the program is dealt with at a time.
2.​ Reduced lines of code: While working with functions, a common set of code is written only once and
can be called from any part of the program which reduces lines of code and programming overheads.
3.​ Easy updation: In case a function is not used in a program, the same set of code which is required in
multiple programs has to be written repeatedly. Hence, if we wish to make any change in a
formula/expression, we have to make changes at every place, else it will result in erroneous or
undesirable output. With function, however, it is required to make changes to only one location (which
is the function itself).

Functions can be categorized into the following three types:


(i) Built-in Functions
(ii) Modules
(iii) User-defined Functions

1. Built-in Functions

Built-in functions are the predefined functions that are already available in Python. FL provide efficiency and
structure to a programming language. Python has many useful functions to make programming easier, faster
and more powerful. These are always available in the standard library and we don't have to import any
module for using them.
Example: int( ), float( ), input( ), max( ), min( ),len( ), round( ), range( ),etc

2. Python Modules
Module is a .py file which contains the definitions of functions and variables.. When we divide a program
into modules then each module contains functions and variables. And each functions is made for a special
task. Once written code in modules can be used in other programs. When we make such functions which
may be used in other programs also then we write them in module. We can import those module in any
program an we can use the functions.

Python provides two ways to import a module -


• import statement: to import full module.

• from: To import all or selected functions from the module.

1
math Module:

random Module:
When we require such numbers which are not known earlier e.g. captcha or any type of serial numbers then
in this situation we need random numbers. And here a random module helps us.
In these types of situations, random numbers are extensively used such as:
1) Pseudo-random numbers on Lottery scratch cards.
2) reCAPTCHA (like, in login forms) uses a random number generator to define which image is to be shown
to the user.
3) Computer games involving throwing of a dice, picking a number, or flipping a coin.
4) Shuffling deck of playing cards, etc.

This contains following functions-


randrange (): This method always returns any integer between given lower and upper limit to this method.
The default lower value is zero (0) and upper value is one(1).

random (): This generates floating value between 0 and 1. it does not require any argument.

2
randint (): This method takes 2 parameters a,b in which first one is lower and second is upper limit. This
may return any number between these two numbers including both limits. This method is very useful for
guessing applications.

User-defined Functions

A function is a set of statements that performs a specific task; a common structuring element that allows you
to use a piece of code repeatedly in different parts of a program.

The use of functions improves a program's clarity and readability and makes programming more efficient by
reducing code duplication and breaking down complex tasks into more manageable pieces. Functions are
also known as routines, sub-routines, methods, procedures or sub-programs.

A user-defined Python function is created or defined by the def statement followed by the function name,
parentheses () and colon (:) as shown in the given syntax:
Syntax:

def function_name(comma_separated_list_of_parameters):

"""docstring"""

Statement(s)

A function definition consists of the following components.

1.​ Keyword def marks the start of the function header.

2.​ A function name to uniquely identify it. Function naming follows the same rules as rules of writing
identifiers in Python.

3.​ Parameters (arguments) through which we pass values to a function. They are optional.

4.​ A colon (:) to mark the end of function header.

5.​ Optional documentation string (docstring) to describe what the function does. It is enclosed in three
double or single quotes and spanned in multiple lines.

6.​ One or more valid Python statements that make up the function body. Statements must have same
indentation level (usually 4 spaces).

7.​ An optional return statement to return a value from the function.

8.​ Function must be called/invoked to execute its code.

3
User-defined Functions without argument and without return:

4
PARAMETERS AND ARGUMENTS IN FUNCTIONS

Parameters are defined by the names (variable(s)) provided in the parentheses when we write function
definition. These variables contain values required by the function to work. These parameters are called
formal parameters.

An argument is a value that is passed to the function when it is called. In other words, arguments are the
value(s) provided in the function call/invoke statement and passed to the variables of formal parameters of
the function. These arguments are called actual parameters or actual arguments. List of arguments should
be supplied in the same way as parameters are listed.

Types of Arguments :
Python supports 4 types of arguments:
1. Positional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable Length Arguments

1. Positional Arguments
• These are the arguments which are passed in correct positional order in function.

• If we change the position of the arguments then the answer will be changed.

5
2. Default Arguments
• These are the arguments through which we can provide default values to the function.
• If we don’t pass any value to the function then it will take a pre defined value.

3. Keyword Arguments
• If a function have many arguments and we want to change the sequence of them then we have to use
keyword arguments.
• Biggest benefit of keyword argument is that we need not to remember the position of the argument.
• For this whenever we pass the values to the function then we pass the values with the argument name.
E.g.

4. Variable Length Arguments


• As we can assume by the name that we can pass any number of arguments according to the requirement.
Such arguments are known as variable length arguments.
• We use (*) asterik to give Variable length argument.

6
SCOPE OF VARIABLES

All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable. Scope of variables refers to the part of the program where it is visible, te, area
where you can refer (use) it. We can say that scope holds the current set of variables and their values. We
will study two types of scope of variables-global scope or local scope.

❖​ Global (module)

1.​ Names assigned at the top level of a module, i.e., outside of any function, or directly in the interpreter

2.​ Names declared with global keyword in a function

3.​ Can be accessed inside or outside of the function

❖​ Local (function)

1.​ Names assigned inside a function definition or loop

2.​ Cannot be accessed outside the function

We can access global variable in the absence of local variable with the same name.

You might also like