Python Functions 1
Python Functions 1
Built-in functions :-
These are the predefined functions which are already available in Python
standard library and can be used in any program.
Some commonly used built-in functions are –
(i) Type conversion functions - These are the functions used to convert one
data type to another.
>>> a=1.5
>>> b="11"
>>> c=int(a)
>>> c
1
>>> d=int(b)
>>> d
11
>>> c="55a"
>>> e=int(c)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
e=int(c)
ValueError: invalid literal for int() with base 10: '55a'
It works as follows –
>>> a = 55
>>> b = float(a)
>>> b
55.0
>>> a = float(5+3)
>>> a
8.0
>>> a = "345"
>>> b = float(a)
>>> b
345.0
If the argument is a string in any other format, it causes
error.
>>> a = "12.34.5"
>>> b = float(a)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
b = float(a)
ValueError: could not convert string to float: '12.34.5'
>>> a = eval('5+3')
>>> a
8
(iii) min() and max() function :- These are used to find out the minimum and
maximum value out of several values. These functions receive several values
as arguments.
>>> abs(-3)
3
>>> abs(5)
5
>>> abs(-6.1)
6.1
(v) type() function :- it takes a variable as argument and returns
the type of value to which the variable refers to.
>>> a = 15
>>> type(a)
<class 'int'>
>>> a = 'abc'
>>> type(a)
<class 'str'>
>>> a = 15.5
>>> type(a)
<class 'float'>
>>> a=[10,20,30]
>>> len(a)
3
>>> b='abcdef'
>>> len(b)
6
>>> round(1.234,2)
1.23
>>> round(1.678,2)
1.68