Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Functions In python

The document provides an overview of functions in Python, explaining their purpose, advantages, and classifications into built-in, module, and user-defined functions. It details various built-in functions, how to import modules, and the syntax for creating user-defined functions, including parameters and return statements. Additionally, it covers variable scope, the flow of execution, and the LEGB rule for variable name resolution.

Uploaded by

iypemarkose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Functions In python

The document provides an overview of functions in Python, explaining their purpose, advantages, and classifications into built-in, module, and user-defined functions. It details various built-in functions, how to import modules, and the syntax for creating user-defined functions, including parameters and return statements. Additionally, it covers variable scope, the flow of execution, and the LEGB rule for variable name resolution.

Uploaded by

iypemarkose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

🎳

Functions in Python
Functions provide a systematic way of problem solving by dividing the given
problem into several sub-problems, finding their individual solutions, and
integrating the solutions of individual problems to solve the original problem.

Function: A function is a group of related statements within a program that


performs a specific task and can be called or invoked from any part of the
program.

Advantages :
Program handling becomes easier

Reduced lines of code and code reusability.

Easy updating of code.

Functions can be classified into : built-in functions, module functions, user-


defined functions.

Built-in functions :
Built-in functions are predefined functions that are already available in python
in the standard library and we don’t have to import any module(file) for using
them.
A) Type conversion functions:

int(): Converts a given value into an integer. If no argument is passed, int()


returns 0.

str(): Converts the argument into a string value.

float(): Converts integers and strings into floating-point numbers. If no


argument is passed, float() returns 0.0 .

B) Mathematical functions :

Functions in Python 1
abs() : Returns the absolute value of a number.

pow() : Returns the value of x to the power of y.

round() : Rounds a number to the nearest integer or to a specified number


of decimal places.

C) input() function: Enables us to accept input from the user.


D) eval() function: Used to evaluate the value of a string. It takes a string as an
argument, evaluates this string as a Python expression, and returns the result.
E) max() and min() : used to find the maximum and minimum value
respectively out of several other values. max() takes two or more arguments
and returns the largest one. min() takes two or more arguments and returns the
smallest item.
F) type() : returns the data type of a variable

>>> x=9
>>> type(x)
<class 'int'> #returns integer for x=9
>>> type(type(x))
<class 'type'>

→ type(type(variable)) returns <class “type”>

G) len() : returns the length of an object. The argument may be


sequence(string,tuple,list) or a mapping (dictionary).

Modules :
A module in Python is a file containing Python definitions and statements. It
allows you to organize related code into a single unit, which can then be
imported and used in other Python programs. Modules help in breaking down
large programs into small manageable and organized files.

#Methods of importing modules

#1 Importing entire module


import <module_name>

#2 Importing selective objects from module

Functions in Python 2
from <module_name> import <objects>

#examples
from math import *
import math

To access/use any of the functions present in the imported modules, we have


to specify the name of the module followed by the name of the function
separated by a dot. This format is called dot notation.

import math
math.sqrt(-1) #gives an error

Module functions:
A) Math module functions:

ceil(x): Returns the smallest integer greater than or equal to a given


number.

floor(x): Returns the largest integer less than or equal to a given number.

pow(x, y): Returns the value of x raised to the power of y.

fabs(x): Returns the absolute value of a number as a float.

sqrt(x): Returns the square root of a number.

log10(x): Returns the base-10 logarithm of a number.

cos(x): Returns the cosine of a number (in radians).

sin(x): Returns the sine of a number (in radians).

tan(x): Returns the tangent of a number (in radians).

B) Random module functions:

randrange(start, stop,[step]): Returns a random integer from a given


range.

By default the lower value is 0 and upper arguement is range-1


Syntax : randrange(stop) OR randrange(start,stop,step)

The stop value is excluded while generating the random number.

Functions in Python 3
random(): Returns a random float between 0 and 1.
1 is excluded : [0.0 , 1.0)

randint(a, b): Returns a random integer between two specified numbers.

a,b are included : [a,b]

uniform(a, b): Returns a random float between two specified numbers.

choice(sequence): Returns a random element from a given sequence.

shuffle(x): Shuffles the elements of a list in place.

User-defined functions :
User-defined functions are custom functions created by programmers to
perform specific tasks, allowing for code reusability and modularity in Python
programs.

Syntax:

def function_name(comma_seperated_list_of_parameters):
"""Doc string"""
statement 1

statements2

return None/ Value

Statements below def begin with four spaces. This is called indentation.

→Keyword def marks the start of a function header.

→Function naming follows the same rule as of writing identifiers in python.

Note : A function that does not contain a return statement is called void
function.

Functions in Python 4
→ Void functions returns a value called None if we try to assign the function to
some variable.

Return statements :
return statement in function is used to end the execution of the function call
and also specifies what value is to be returned back to the calling function..
→ Python the supports returning of multiple values.

def add_sub(x,y):
add=x+y
sub=x-y

return add,sub #returning of multiple values.

sum,difference=add_sub(10,20)

Actual parameters and formal Parameters :


→ Actual parameter : parameter that appears in the function call or it is the
value that is passed in to the function when it is invoked.

→ Formal parameter : variables/names that appear in the function header in the


parenthesis or the parameters that appear in the function definition.

Types of arguments:
Positional arguments :

They are arguments that are passed in to the function in the correct
positional order, i.e , in the same order as in the function header.
They are also known as required arguments.

Default arguments :

It is an argument that can assign a default value if a value is not provided in


the function call for that argument. The default value is assigned at the time
of function definition by the assignment(=) operator.

Functions in Python 5
def greet_msg(msg="good morning"):
print(msg)

greet()
greet("hi bye")

Keyword arguments :
This allows to call functions with arguments in any order using the name of
the arguments. They can be placed in any order in the function call.

Advantages :

Using function with keyword arguments is easier as we do not need to


remember the order of the arguments

We can specify values of only those parameters which we want to, as


other parameters have default arguments.

Variable-length arguments :

Variable-length arguments allow a function to accept any number of


arguments. This is useful when you don't know beforehand how many
arguments will be passed to your function. In Python, there are two ways to
specify variable-length arguments:

*args: Used to pass a variable number of non-keyword arguments to a


function.

**kwargs: Used to pass a variable number of keyword arguments to a


function.

def sum(*n):
total=0
for i in n:
total+=i
print(total)

sum() #returns 0
sum(20,30) #returns 50

Functions in Python 6
sum(10,20,30,40) #returns 100

def sum(**n):
print(n) #{'n': (10, 20, 30, 40)}
total=0
for i in n["n"]:
total+=i
print(total)

sum(n=(10,20,30,40)) #returns 100

Important points to be noted :


Keyword arguments should not be before the positional arguments.

Multiple values should not be given for the same parameter.

#consider the function


def average(n1,n2,n3=300):
return (n1+n2+n3)/3

average(n3=70,n1=20,100) #keywords arguments should not be


before positional arguments
#so this line gives an error

average(20,n1=23,n2=1) #gives an error


#multiple values provided for n1

Scope of variables :
Scope of a variable refers to part of the program where it is visible i.e, area
where we can refer (use) it.
Global variables:

Functions in Python 7
Global variables are variables defined outside of any function or class,
accessible from anywhere in the program.

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

Names declared with global keyword in a function

Can be accessed inside or outside from the function

Life time of global variable : entire program run (i.e they live in memory as
long as the program is running)

Local variables:
Local variables are variables defined within a function and are only accessible
within that function's scope.

Names assigned inside a function or loop

Life time is their function’s run (i.e as long as their function is being
executed)

Flow of execution :
It can be defined as the order in which the statements in a program are
executed. The python interpreter starts executing the instructions in a program
from the first statement. The statements are executed one by one, in order of
appearance from top to bottom.
→ If a def statement is encountered all other statements of the functions are
skipped but the function header is interpreted to check if it’s valid.
→ If a function call is encountered the statements in the called function are
executed from top-bottom.

LEGB rule :
The LEGB rule defines the order in which Python looks up variable names. It
stands for Local, Enclosing, Global, and Built-in. This rule determines the scope
of variables and how they are resolved in a Python program.

It checks within its Local environment or local namespace.

If not resolved, Python now checks the Enclosing environment.

Functions in Python 8
Then checks the Global environment

Finally the Built-in environment.

Illustration :

from math import pi #built-in scope

def outside():
pi=20 #enclosing scope

def inside():
pi=30 #local scope
return pi

return inside()

pi=40# global scope


print(outside())

Functions in Python 9

You might also like