# Python Data Persistence – Built-in Functions

## Python Data Persistence – Built-in Functions

Python interpreter contains a number of built-in functions. These functions can always be used. You have come across a couple of them in previous sections (type () and id()). In this section, few more built-in functions are being introduced. Some of them will come up for discussion in subsequent chapters. A full list of built-in functions is attached in appendix A.

Number Conversion Functions

A numeric object of one type can be converted to other by using the following built-in functions. These functions have a name that is the same as the built-in data type.

1. int ( ): Function returns an integer from a float or a string of digit characters.

Example

>>> #float to integer
>>> int(10.55)
10
>>> int(0.546)
0
>>> #int from string . .. int('12’)
12

The string of digits returns to an integer according to the decimal number system i.e. base is assumed to be 10. For conversion of string to octal, or hexadecimal integer, the function needs the base – 8 or 16 as the second parameter. Knowing ‘72’ in octal is equivalent to 10 (Ten) and ‘72’ in Hexadecimal is equivalent to 18 (Eighteen). Incidentally, the alphabets ABCDEF are also Hexadecimal digits and hence get converted to their integer equivalents.

Example

>>>
int ( '12' ,8)
10
> > > int ('12',16)
18
> > > int ('C',16)
12

2. float ( ): Function returns a floating object from any number or a string containing valid floating-point number representation, either with . decimal point or with scientific notation symbol e or E.

Example

>>> #float from string with decimal notation
. . .
>>> float ( ' 3 .142 ' )
3.142
>>> #float from scientific notation
. . .
>>> float ( ' 1.501E2 ' )
150.1

3. complex( ): Function creates a complex number object out of two parameters given to it. the First parameter is treated as the real part of the complex number and the real part is the second one multiplied by imaginary number j makes up the imaginary part. So, complex(x,y) returns x+yj.

The second argument is optional and is considered 0 by default. Both arguments can be integer, float, or even a complex number.

Example

>>> #complex from integer parameters
. . .
>>> complex(5,6)
(5+6j)
>>> #complex from float parameters
. . .
>>> complex(2.2,-3.5)
(2.2-3.5j)
>>> #complex from complex number parameters
. . .
>>> complex(2+3j,1+2j)
4j

When a second parameter is a complex number, the result is calculated by multiplying it with l+0j and adding the first parameter to it. Hence,

Example

 2 + 3j +(1 + 2j)*1 . 0j = 4j

If the first parameter is a string representation of a complex object, there shouldn’t be a second parameter. There shouldn’t be any space within the string.

Example

>>> #complex from string
. . .
>>> complex('1+2j')
(1+2j)
>>> #space not allowed
. . .
>>> complex('1 + 2j')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex( ) arg is a malformed string

Conversely real and imaginary components can be separated by a complex number of objects using ‘real’ and ‘imag’ attributes.

Example

>>> c1=complex('1+2j')
>>> #real part
. . .
>>> cl.real
1.0
>>> #imaginary part ... cl.imag
2,0

4. bool ( ): Function evaluates given parameter and returns True or False. It needs one parameter. If it is a non-zero number or an expression that evaluates to a non-zero number, the function returns True, otherwise, it returns False.

Example

>>> #boolean value of integer
. . .
>>> bool(20)
True
>>> bool(-11)
True
>>> bool(0)
Faise
>>> bool(10-5*2)
False
>>> bool(10%2)
False

A non-empty sequence, as well as a dictionary object as a parameter, makes this function True.

Example

>>> #boolean value of sequence
. . .
>>> bool([1,2,3])
True
>>> bool ( [] )
False
>>> bool('') #empty string
False
>>> bool('Hello')
True
>>> bool((1,2,3)) #tuple
True
>>> bool(())
False
>>> bool({1:'one',2:'two'}) #dictionary True
>>> bool({})
False

The bool( ) function also returns True if it receives any logical expression that evaluates to True. Under all other circumstances, bool() returns False.

Example

>>> #boolean value of logical expression
. . .
>>> bool(10>5)
True
>>> bool(3 in [1,2,3,4])
True

Built-in Mathematical Functions

This section introduces some important mathematical functions from the built-in function library.

1. abs ( ): Function returns the absolute value of the parameter, which can be integer, float, or complex number.

Example

>>> #absolute of integer
. . .
>>> abs(-256)
256
>>> #absolute of integer
. . .
>>> abs(1.2E-3)
0.0012
>>> #absolute of complex
. . .
>>> abs(2-3j)
3.605551275463989

2. divmod( ): Function performs division of two parameters and returns division and remainder in the form of a tuple.Absolute value of complex number a+bj is calculated as $$\sqrt{a^{2}+b^{2}}$$

Example

>>> a=divmod(10,3)
> > > a
(3, 1)

3. pow( ): Function performs exponent computation. It takes two numeric parameters. pow(x,y) returns x to the power y (or x raised to y). This is equivalent to exponent operator x**y

Example

>>> pow(10,2)
100
>>> pow(27,1/3)
3.0

4. round ( ): Function returns a number by rounding the parameter to the precision of desired digits before/after the decimal point. the First parameter is the number to be rounded. The second parameter is the digits up to which it is to be rounded. If the digit at the position next to desired precision is greater than 5, then the last digit is increased by 1 and the remaining digits are dropped.

Example

> > > round(123 453467,4)
123.4535
> > > round(123 453467,2)
123.45
>>> round(123 453467,1)
123.5

If the second parameter is 0, then the entire fraction part is considered. If it is greater than 0.5, the return value of the round( ) function is integer part +1, otherwise, only the integer part is returned.

Example

>>> round(123.453467,0)
123.0
>>> round(10/6,0)
2.0

If the second parameter is negative, then the integer part is rounded towards the left of the decimal point.

Example

>>> round(123.453467,-1)
120.0
>>> round(123.453467,-2)
100.0

Sequence Functions

Following functions act on sequence objects (also called tables) such as string, list, and tuple.

1. max ( ): In the case of a list or tuple consisting of numeric items (excluding complex numbers), the largest number is returned. If the list/tuple is made of strings, the one that appears last in alphabetical order is returned. For a string object, the max() function returns a character with the highest ASCII value.

2. min ( ): Function returns the smallest number from list/tuple of numeric items. The string that appears first in alphabetical order is returned by this function if list/tuple is made up of string items. For a single string, the min( ) function returns a character with the lowest ASCII value.

Example

>>>#max/min of numeric items
. . .
>>> tup1=(-50, 3.142,True, 50, pow(8,2) ,1.001e-2)
>>> max(tup1)
64
>>> min(tup1)
-50
>>> #max/min of string items
. . .
>>> list1=['Python', 'Java', 'C++', 'Ruby', 'Kotlin'] >>> max(listl)
'Ruby'
>>> min(list1)
' C++ '
>>> #max/min in a string
. . .
>>> str1='Monty Python and the Holy Grail'
>>> max(str1)
' y'
>>> min(str1)
' '

3. len ( ): In addition to sequence types, this function is also used with dictionary objects. It returns a number of items in sequence/dictionary.

Example

>>> str1='Monty Python and the Holy Grail'
>>> len(str1)
31
>>> list1=['Python', 'Java', 'C++', 'Ruby', 'Kotlin']
>>> len(listl)
5
>>> tup1=(-50, 3.142,True, 50, pow(8,2) ,1.001e-2)
>>> len(tup1)
6
>>> len(dict1)
3

4. list () : Function returns a new list object. If there is no parameter given, an empty list object is created. If a string parameter is used, every character becomes an item in the list object. If a tuple parameter is used, it returns a mutable version of the same items.

Example

>>> list ( )
[ ]
>>> list('Hello Python')
['H' , 'e' , 'l' ,'l' , 'o' , ' ' , 'p' , 'y' , 't' , 'h' , 'o' , 'n']
>>> tup1= ( -50, 3.142, True, 50, pow(8,2),1 001e-2)
>>> list(tup1)
[-50, 3.142, True, 50, 64, 0.01001]

5. tuple ( ): Function returns a new tuple object. If no parameter is given, then an empty tuple object is created. If a string parameter is used, every character becomes an item in the tuple object. If the parameter is a list, it returns an immutable version of the same items.

Example

>>> tuple ( )
( )
>>> tuple('Hello Python')
['H' , 'e' , 'l' ,'l' , 'o' , ' ' , 'p' , 'y' , 't' , 'h' , 'o' , 'n']
>>> list1= (-50, 3.142,True, 50, pow(8,2),1.001e-2)
>>> tuple(list1)
(-50, 3.142, True, 50, 64, 0.01001)

6. str ( ): Function returns a string representation of any Python object. If no parameter is given an empty string is returned.

Example

>>> str ( )
' '
>>> str (1101)
'1101'
>>> str (3.142)
'3.142'
>>> str ([1,2,3])
'[1,2,3]'
>>> str ( (1,2,3))
'(1,2,3)'
>>> str({1: 'one' , 2: 'two' , 3: 'three'})
"{1: ' one ' , 2: 'two' , 3: 'three'}"

Python’s built-in function library has input () and print () functions. The former reads user input and the latter displays output. These functions are meant more for scripting mode rather than interactive mode, although you can them in Python shell as well.10 functions

1. input ( ): When this function is encountered, a Python interpreter waits for input from the input device, the default being the keyboard. The function returns a string object made up of all keys entered by the user until entering the key. You can use a string parameter inside function parentheses to prompt the user about what to input. The return value of the function is usually stored in a string variable for further processing.

Example

>>> name=input( enter your name_')
>>> name
'Ramkrishna'

2. print ( ): Function displays the value of one or more objects on Python console (if used in interactive mode) or DOS window (if used in scripting mode). In interactive mode, any expression anyway echoes in next line when entered in front of Python prompt >>>.

Example

>>> 2+2
4
>>> print (2+2)
4

This function plays a very important role in displaying output in scripting mode as we shall see soon. There can be multiple comma-separated parameters in the function’s parentheses. Their values are separated by ‘ ‘ although separation character can be changed if you want. For example, if you want ‘,’ between two values, use the sep parameter.

Example

>>> name=' Ram'
>>> age=20
>>> marks= 50
>>> print (name, age, marks)
Ram 20 50
>>> print (name, age, marks, sep=',1)
Ram,20,50

Python scripts become extremely powerful with the use of input() and print() functions. The result of a certain process with different user inputs can be displayed as following: First, using a suitable text editor, type and save the following code as ‘hello.py.

Example

#hello.py
name = input(1 enter your name:')
print ('Hello', name, 'how are you?')

Now, run this script from the command line (figure 1.5):

C : \ Users \ acer>Python hello . py
Hello Maya how are you?

Run it again with different input and get the corresponding output, figure 1.6)

C : \ Users \ acer >Python hello . py
Hello Mahesh how are you?


Remember that the input () function always returns a string object. What if you want numeric input from the user? This is where you have to use different number conversion functions (like int (), float () and so on.) we studied earlier. The following script reads length and breadth from the user and computes the area of a rectangle.

Example

Output:

C : \ Users \ acer>Python area . py
enter length : 20
enter breadth : 30 area = 600

C : \ Users \ acer>Python area . py
enter length : 25
enter breadth : 35 area : 875

The print ( ) function issues an EOF character (‘\n) at the end. The output of the next print ( ) statement appears below the current line. To make it appear in the same line, specify the ‘end’ parameter to some other characteristics such as ‘ Look at the following modified version of ‘area.py’ script:

Example

C : \ Users \ acer>Python area . py
length : 20 breadth : 30 area = 600