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

Built in Functions

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

Built in Functions

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

Function and Built in functions in python

A function typically performs a specific task that you can run in your program.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ().
 Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Example:

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Result:
I'm first call to user defined function!
Again second call to the same function

Function Arguments
You can call a function by using the following types of formal arguments −
1
Function and Built in functions in python

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. 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.
def add(a,b):
c=a+b
print(c)
add(5,7)
add(10,20)

result:
12

30

2. 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.
Example:
def display(x,y):
print("x=",x)
print("y=",y)
display(10,20)#required argument
display(x=50,y=70)#keyword argument
display(y=12,x=40)#keyword argument

Result:
x= 10

y= 20

x= 50

y= 70

x= 40

2
Function and Built in functions in python

y= 12

3. 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.
Example:
def display(x,y=0):
print("x=",x)
print("y=",y)
display(10,20)#required argument
display(x=50,y=70)#keyword argument
display(y=12,x=40)#keyword argument
display(37)# default argument

Result:
x= 10

y= 20

x= 50

y= 70

x= 40

y= 12

x= 37

y= 0

4. Variable-length arguments:
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-lengtharguments and are not named in the
function definition, unlike required and default arguments.
Syntax:

def functionname([formal_args,] *var_args_tuple ):

"function_docstring"

function_suite

return [expression]

Example:

def display(*arg):
3
Function and Built in functions in python

for i in arg:
print(i)
print("First call")
display(20)
print("Second call")
display(30,40,50)

Result:

First call

20

Second call

30

40

50

Return Multiple Values:

You can return multiple values from a function by separating them with a comma. This
actually creates a tuple, which you can use as is, or unpack in order to use the individual
values.

Example:

# Function to perform the four basic arithmetic operations


# against two numbers that are passed in as arguments.
def basicArithmetic(x, y):
# Do the calulations and put each result into a variable
sum = x + y
product = x * y
quotient = x / y
difference = x - y
# Return each variable
return sum, product, quotient, difference
# Call the function and print the result
print(basicArithmetic(3, 30))
a,b,c,d=basicArithmetic(3,30)
print("a=",a)
print("b=",b)
print("c=",c)
print("d=",d)

4
Function and Built in functions in python

Result:
(33, 90, 0.1, -27)

a= 33

b= 90

c= 0.1

d= -27

Built in functions:

abs() delattr() hash() memoryview() set()


all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod( getattr() locals() repr() zip()
)
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

S.No Function Description Example


1 abs() Return the absolute value of a >>> abs(5)
number. The argument may be 5
an integer or a floating point >>> abs(5.6)
number. If the argument is a 5.6
complex number, its magnitude >>> abs(-6.7)
is returned. 6.7
>>>
2 all() Return True if all elements of >>> l=[1,2,3,4,5]
the iterable are true (or if the >>> all(l)
iterable is empty). True
>>> l1=[]
>>> all(l1)
True
>>> l2=[-5,6,7,-9,0]
>>> all(l2)
False
>>> l3=[True,False]
>>> all(l3)

5
Function and Built in functions in python

False
>>>
3 any() Return True if any element of >>> l=[1,2,3,4,5]
the iterable is true. If the >>> l1=[]
iterable is empty, return False. >>> l2=[-5,6,7,-9,0]
>>> l3=[True,False]
>>> any(l1)
False
>>> any(l)
True
>>> any(l2)
True
>>> any(l3)
True
>>>
4 ascii() return a string containing a
printable representation of an
object, but escape the non-
ASCII characters in the string
returned by repr() using \x, \u
or \U escapes
The non-ASCII characters in
the string is escaped using \x, \u
or \U.
5 bin() Convert an integer number to a >>> bin(10)
binary string prefixed with “0b” '0b1010'
>>> bin(-6)
'-0b110'
6 bool() Return a Boolean value, i.e. one >>> bool(10)
of True or False. f x is false or True
omitted, this returns False; >>> bool(-9)
otherwise it returns True True
>>> bool()
False
>>>
7 chr(i) Return the string representing a >>> chr(97)
character whose Unicode code 'a'
point is the integ >>> chr(89)
'Y'

8 complex([real[, imag]]) Return a complex number with >>> complex(10,20)


the value real + imag*1j or (10+20j)
convert a string or number to a >>> complex(10)
complex number. If the first (10+0j)
>>> complex()
parameter is a string, it will be
0j
interpreted as a complex >>> complex("10")
number and the function must (10+0j)
be called without a second
parameter. The second
6
Function and Built in functions in python

parameter can never be a string.


Each argument may be any
numeric type (including
complex). If imag is omitted, it
defaults to zero and the
constructor serves as a numeric
conversion like int and float. If
both arguments are omitted,
returns 0j.

9 dir([object]) >>> import math


Without arguments, return the
>>> dir(math)
list of names in the current local
scope. With an argument, ['__doc__', '__loader__',
'__name__',
attempt to return a list of valid
'__package__',
attributes for that object.
'__spec__', 'acos', 'acosh',
'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil',
'copysign', 'cos', 'cosh',
'degrees', 'e', 'erf', 'erfc',
'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod',
'frexp', 'fsum', 'gamma',
'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf',
'isnan', 'ldexp', 'lgamma',
'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'pi',
'pow', 'radians',
'remainder', 'sin', 'sinh',
'sqrt', 'tan', 'tanh', 'tau',
'trunc']
>>>
10 dict() Create a new dictionary. >>> d={1:1,2:4,3:9,4:16}
>>> d
{1: 1, 2: 4, 3: 9, 4: 16}
>>> dict()
{}
11 divmod(a, b) Take two (non complex) >>> divmod(10,3)
numbers as arguments and (3, 1)
return a pair of numbers
consisting of their quotient and
remainder when using integer
division.
12 enumerate(iterable, start=0) Return an enumerate >>> s="swarnandhra"
object. iterable must be a >>> enumerate(s,start=1)
sequence, an iterator, or some <enumerate object at
0x022EED50>
7
Function and Built in functions in python

other object which supports >>>


iteration list(enumerate(s,start=1))
[(1, 's'), (2, 'w'), (3, 'a'),
(4, 'r'), (5, 'n'), (6, 'a'), (7,
'n'), (8, 'd'), (9, 'h'), (10,
'r'), (11, 'a')]
>>> list(enumerate(s))
[(0, 's'), (1, 'w'), (2, 'a'),
(3, 'r'), (4, 'n'), (5, 'a'), (6,
'n'), (7, 'd'), (8, 'h'), (9, 'r'),
(10, 'a')]
>>>
13 eval(expression, globals=N The return value is the result of >>> x=5
one, locals=None) the evaluated expression. >>> eval('x+5')
10
>>> eval('x-8')
-3
14 float([x]) returns a floating point number >>> float("6.7")
constructed from a number or 6.7
>>> float(8)
string x. 8.0
>>> float("Infinity")
Inf
>>> float("23e6")
23000000.0

15 format(value[, format_spec] Convert a value to a >>> '{0}, {1},


) {2}'.format('a', 'b', 'c')
“formatted” representation,
'a, b, c'
ascontrolled by format_spec. >>> '{}, {},
{}'.format('a', 'b', 'c') #
3.1+ only
'a, b, c'
>>> '{2}, {1},
{0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1},
{0}'.format(*'abc') #
unpacking argument
sequence
'c, b, a'
>>> '{0}{1}
{0}'.format('abra', 'cad')
# arguments' indices can
be repeated
'abracadabra'
16 frozenset([iterable]) Returns a new frozenset object,
optionally with elements taken
from iterable.
17 hex(x) Convert an integer number to a >>> hex(15)
8
Function and Built in functions in python

lowercase hexadecimal string '0xf'


>>> hex(16)
prefixed with “0x”
'0x10'
18 id(object) Return the “identity” of an
object.

19 input([prompt]) If the prompt argument is


present, it is written to standard
output without a trailing
newline

20 len(s) Return the length (the number >>> s="hello"


>>> len(s)
of items) of an object.
5
21 list([iterable]) Rather than being a function, >>> s="hello"
list is actually a mutable >>> s
'hello'
sequence type >>> list(s)
['h', 'e', 'l', 'l', 'o']
>>>
22 max(iterable, *[, key, defaul Return the largest item in an >>> s="hello"
t]) >>> max(s)
iterable or the largest of two or
max(arg1, arg2, *args[, key 'o'
]) more arguments. >>> max(10,20,3,67,89,-
30)
89
23 min(iterable, *[, key, default Return the smallest item in an >>> s="hello"
]) >>> min(s)
iterable or the smallest of two
min(arg1, arg2, *args[, key] 'e'
) or more arguments. >>> min(10,20,3,67,89,-
30)
-30
24 next(iterator[, default]) Retrieve the next item from
the iterator
25 oct(x) Convert an integer number to >>> oct(56)
'0o70'
an octal string prefixed with
>>> oct(8)
“0o”. '0o10'

26 open(file, mode='r', bufferin Open file and return a


g=-1, encoding=None, erro corresponding file object. If the
rs=None, newline=None, cl
osefd=True, opener=None) file cannot be opened,
an OSError is raised.

9
Function and Built in functions in python

27 ord(c) Given a string representing one >>> ord('a')


97
Unicode character, return an
>>> ord('A')
integer representing the 65
Unicode code point of that
character.

28 pow(x, y[, z]) Return x to the power y; if z is >>> pow(5,2)


25
present, return x to the power y,
>>> pow(5,2,3)
modulo z (computed more 1
efficiently than pow(x, y) % z).
The two-argument
form pow(x, y) is equivalent to
using the power operator: x**y.

29 print(*objects, sep=' Print objects to the text


', end='\n', file=sys.stdout, fl stream file, separated
ush=False)
by sep and followed
by end. sep, end, file and flush,
if present, must be given as
keyword arguments.
30 range(stop) Rather than being a
range(start, stop[, step]) function, range is actually an
immutable sequence type

31 repr(object) Return a string containing a >>> s="hello"


printable representation of an >>> repr(s)
"'hello'"
object

32 reversed(seq) Returns reverse iterator. >>> s="hello"


>>> reversed(s)
<reversed object at
0x02292FD0>
33 round(number[, ndigits]) Returns number rounded to >>>
round(10.3234561,2)
ndigits precision after the
10.32
decimal point. If ndigits is >>>
omitted or is None, it returns round(10.3563213456,2)
the nearest integer to its input. 10.36

10
Function and Built in functions in python

34 sum(iterable[, start]) Sums start and the items of >>> l=[1,2,3,4,5]


>>> sum(l,0)
an iterable from left to right
15
and returns the>>> sum(l,10)
total. start defaults to 0 25
35 sorted(iterable, *, key=Non Return a new sorted list from >>> s="hello"
e, reverse=False) >>> sorted(s)
the items in iterable.
['e', 'h', 'l', 'l', 'o']

36 tuple([iterable]) Rather than being a >>> l=[1,2,3,4,5]


function, tuple is actually an >>> tuple(l)
(1, 2, 3, 4, 5)
immutable sequence type
37 class type(object) With one argument, return the >>> l=[1,2,3,4,5]
class type(name, bases, dict >>> type(l)
type of an object.
) <class 'list'>

38 zip(*iterables) Make an iterator that aggregates >>> l=[1,2,3,4,5]


>>> l1=[1,4,9,16,25]
elements from each of the
>>> x=zip(l,l1)
iterables. zip() should only be >>> x
used with unequal length inputs <zip object at
when you don’t care about 0x02270080>
trailing, unmatched values from >>> list(x)
[(1, 1), (2, 4), (3, 9), (4,
the longer iterables.
16), (5, 25)]

>>> l2=[0,0,0]
>>> y=zip(l,l2)
>>> y
<zip object at
0x022700A8>
>>> list(y)
[(1, 0), (2, 0), (3, 0)]

11

You might also like