0% found this document useful (0 votes)
76 views

Python-FUNCTIONS by Vivek Singh Khetwal.

1) Functions allow programmers to organize code into reusable blocks to perform tasks. Functions can take in data as arguments, perform operations on that data, and return results. 2) In Python, functions are defined using the def keyword and can take different argument types, including required, keyword, default, and variable-length arguments. 3) There are three types of functions in Python: built-in functions that are predefined in the language, user-defined functions created by programmers, and anonymous functions.

Uploaded by

V VÈk ŞınGh
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)
76 views

Python-FUNCTIONS by Vivek Singh Khetwal.

1) Functions allow programmers to organize code into reusable blocks to perform tasks. Functions can take in data as arguments, perform operations on that data, and return results. 2) In Python, functions are defined using the def keyword and can take different argument types, including required, keyword, default, and variable-length arguments. 3) There are three types of functions in Python: built-in functions that are predefined in the language, user-defined functions created by programmers, and anonymous functions.

Uploaded by

V VÈk ŞınGh
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/ 10

PYTHON – FUNCTIONS

Functions:

In computer programming the programs are broken up into functions for better
modularity and ease of maintenance. A function can be defined as a block of code
that takes in some data either for performing some operations using that data and
returns the operated data or performs some task on that data.

Similar kind of data can be stored inside a function and we can provide a name to
that function that can describe its functionality. Functions in Python are similar to
the functions in C++ and Java. The functionality is same only the syntax differs
from other programming languages.

A function is a piece of code written to carry out a specified task. To carry out that
specific task, the function might or might not need multiple inputs. When task is
carried out a function might or might not return one or more values.
Functions in Python are defined using the def keyword.

Example1:
def hello():
print('Hello! I am Vivek.’)

Example2: def sum(x,y):


return(x+y)
sum(5,6)

Fig: The example above is showing the use of def keyword while defining a function.

There are 3 types of functions in Python:


1. Built-in functions.
2. User-defined functions.
3. Anonymous functions.

By- Vivek Singh Khetwal (54086)


1) Built-In Functions:
The Python built-in functions are the functions whose functionality is pre-
defined in Python. The Python interpreter has several functions that are
always present for use. The functions are known as Built-in Functions. There
are several built-in functions in python such as, max() is used to get the
maximum value, input() is used to take the user input, print() is used to print
an object to terminal.

Method Description

abs() returns absolute value of a number

all() returns true when all elements in iterable is true

any() Checks if any Element of an Iterable is True

ascii() Returns String Containing Printable Representation

bin() converts integer to binary string

bool() Converts a Value to Boolean

bytearray() returns array of given byte size

bytes() returns immutable bytes object

callable() Checks if the Object is Callable

chr() Returns a Character (a string) from an Integer

classmethod() returns class method for given function

compile() Returns a Python code object

complex() Creates a Complex Number

delattr() Deletes Attribute From the Object

dict() Creates a Dictionary

dir() Tries to Return Attributes of Object

divmod() Returns a Tuple of Quotient and Remainder

enumerate() Returns an Enumerate Object

eval() Runs Python Code Within Program

exec() Executes Dynamically Created Program

By- Vivek Singh Khetwal (54086)


Method Description

filter() constructs iterator from elements which are true

float() returns floating point number from number, string

format() returns formatted representation of a value

frozenset() returns immutable frozenset object

getattr() returns value of named attribute of an object

globals() returns dictionary of current global symbol table

hasattr() returns whether object has named attribute

hash() returns hash value of an object

help() Invokes the built-in Help System

hex() Converts to Integer to Hexadecimal

id() Returns Identify of an Object

input() reads and returns a line of string

int() returns integer from a number or string

isinstance() Checks if a Object is an Instance of Class

issubclass() Checks if a Object is Subclass of a Class

iter() returns iterator for an object

len() Returns Length of an Object

list() creates list in Python

locals() Returns dictionary of a current local symbol table

map() Applies Function and Returns a List

max() returns largest element

memoryview() returns memory view of an argument

min() returns smallest element

next() Retrieves Next Element from Iterator

object() Creates a Featureless Object

oct() converts integer to octal

By- Vivek Singh Khetwal (54086)


Method Description

open() Returns a File object

ord() returns Unicode code point for Unicode character

pow() returns x to the power of y

print() Prints the Given Object

property() returns a property attribute

range() return sequence of integers between start and stop

repr() returns printable representation of an object

reversed() returns reversed iterator of a sequence

round() rounds a floating point number to ndigits places.

set() returns a Python set

setattr() sets value of an attribute of object

slice() creates a slice object specified by range()

sorted() returns sorted list from a given iterable

staticmethod() creates static method from a function

str() returns informal representation of an object

sum() Add items of an Iterable

super() Allow you to Refer Parent Class by super

tuple() Function Creates a Tuple

type() Returns Type of an Object

vars() Returns __dict__ attribute of a class

zip() Returns an Iterator of Tuples

__import__() Advanced Function Called by import

Given above, are the built-in functions present in python.

By- Vivek Singh Khetwal (54086)


2) User-Defined Functions:
User-defined functions are the functions that are created by the users
themselves. Below are the steps for defining a function in Python.
 In Python a user-defined function’s declaration begins with the keyword
def and followed by the function name.
 The functions may take one or more arguments as input within the
opening and closing parenthesis “( )”, just after the function name
followed by the colon “:”.
 After defining the function name and arguments a block of program
statements start at the next time and these statements must be indented.
Syntax of User-defined Functions:

def function_name(argument_1, argument_2,….):


Statement_1
Statement_2
…….

The return statement


The return statement causes your function to exit and hand back a value to
its caller. The point of functions in general is to take in inputs and return
something. The return statement is used when a function is ready to return
a value to its caller.
For example, here is a function utilizing both print() and return:

def greet():
print(“Hello! How are you?”)
return 1

Now you can run code that calls greet function:

If __name__== ‘__main__’:
print(“ going to call greet ”)
x=greet
print(“ called greet ”)
print(“ foo returned ” + str(x))

Output:

going to call greet


Hello! How are you?
Called greet
Greet returned 1

By- Vivek Singh Khetwal (54086)


Calling a User-defined Function:
Calling a function means that you execute the function that you have
defined either directly from the Python prompt or through another function.
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code. Once the
basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the
example to call sum() function:

# This is function definition


def sum(a, b):
return(a+b)
# This is the function calling
sum(8, 10)
sum(5, 7)

The above code produces the following result:

18
12

Function Arguments
In Python, user-defined functions can take four different types of arguments.
The argument types and their meanings, however, are pre-defined and
cannot be changed. But a user can use these pre-defined rules to make their
own custom functions.
One can call a function by using the following types of formal arguments:
a) Required Arguments.
b) Keyword arguments.
c) Default arguments.
d) Variable-length arguments.

By- Vivek Singh Khetwal (54086)


Required Arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.

Function definition:

def nameAge( str, num):

Function Call:

nameAge( “Vivek”, 21)

Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.

Function definition:

def keywordArg( name, role):

Function Call:

keywordArg( name = “Vivek”, role = “Student” )

or

keywordArg( role = “Student”, name = “Vivek” )

By- Vivek Singh Khetwal (54086)


Default Arguments

A default argument is an argument that assumes a default value if a value is


not provided in the function call for that argument. The default value is
assigned by using assignment (=) operator. Below is the syntax for default
argument. Here, msg parameter has a default value Hello! .

Function Definition:

def defaultArg( name, msg = “Hello!” ):

Function Call:

defaultArg( Vivek )

Variable-Length Arguments

This type of argument is very useful when we do not know the exact number
of arguments that will be passed to a function. Or we can have a design
where any number of arguments can be passed based on the requirement.

Function Definition:

def varlenthArgs( *varargs ):

Function Call:

varlengthArgs(30, 40, 50, 60)

By- Vivek Singh Khetwal (54086)


3) Anonymous Functions:
In Python, anonymous function is a function that is defined without a name.
Anonymous functions in Python are also known as lambda functions.
Normal functions in Python are defined using ‘def’ keyword whereas
anonymous functions are defined using the lambda keyword.
A lambda function in Python has following syntax:

lambda arguments:expression

Program:

int = lambda x : x*2


print(int(10))

Output:

20

In above program lambda x:x*2 is lambda functions. Here x is the argument


and x*2 is expression.
It returns a function object which is assigned to the identifier ‘int’.

int = lambda x : x * 2

Above syntax is similar to:

def int( x ):
return( x * 2 )

In Python we use lambda functions when we require a nameless function for


a short period of time. One typically writes lambda function, when one wants
to write a function for one time use.
The power of lambda function can be realized only when it is used as part of
another function They can be used along with the python’s built-in functions
line filter(), map(), etc.

By- Vivek Singh Khetwal (54086)


Using lambda with map()
With filter function, we can filter a list based on condition specified by a
lambda function. For example, here we are filtering the list with condition of
element in the list is greater than 10. The result from filter is a smaller list
with elements satisfying the condition specified by lambda function.

my_list = range(20)
map(lambda x : x * 2, my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

Using lambda function with filter()


With filter function, we can filter a list based on condition specified by a
lambda function. For example here we are filtering the list with condition of
element in the list is greater than 10. The result from filter is a smaller list
with elements satisfying the condition specified by lambda function.

my_list = range(20)
filter(lambda x: x > 10 my_list)
[11, 12, 13, 14, 15, 16, 17, 18, 19]

By- Vivek Singh Khetwal (54086)

You might also like