# Python Data Persistence – Structured Python

## Python Data Persistence – Structured Python

The previous two chapters explained some basic features of Python, which will empower you to develop a programming solution for just about any algorithm. Now it’s time to learn how to make the solution more tidy, efficient, and easy to maintain.
In the previous chapter, the factorial.py code calculates the factorial value of a number. Based on the same algorithm, let us calculate a combination of two numbers. In mathematics, a combination is a selection of items from a collection, such that (unlike permutations) the order of selection does not matter. Its mathematical notation is nCr. Following script uses for loop in its solution.

Example

#combinations.py
n=int ( input ( " enter n . . " ) )
r=int ( input ( " enter r . . " ) )
t=n-r
#calculating factorial of n - fn
fn=1
for i in range ( 1 ,n+1 ) :
fn=fn*i
#calculating factorial of r - fr
fr=1
for i in range(1,r+1):
fr=fr*i
#calculating factorial of t - tr
ft = 1
for i in range ( 1 , t+1 ) :
ft=ft*i
combinations=fn/(fr*ft)
print ( " C ( { } , { } )={ }". format ( n , r , combinations ) )

Output

E:\python37>python combinations.py
enter n . . 5
enter r . . 2
C ( 5 , 2 ) = 10 . 0
E:\python37 >python combinations.py
enter n . . 10
enter r . . 5
C ( 10 , 5) = 252 . 0

Looks alright, isn’t it? However, looking at the above code, the thing that strikes immediately is that it uses for loop thrice to calculate the factorial value of three numbers. Following code is the alternative solution to the same problem but appears to be cleaner and more concise.

Example

#combinations-2.py
#calculate factorial
def factorial ( x ) :
f = 1
for i in range ( 1 , x+1 ) :
f = f*i
return f
n=int ( input ( " enter n . . " ) )
r=int ( input ( " enter r . . " ) )
combinations=factorial(n)/
(factorial(r)*factorial(n-r))
print ( " C ( { } / { } )={ } " - format ( n , r , combinations ) )

sys Module

This module defines some important system-specific parameters and functions. In this section, you will learn one such parameter which is useful in the scripting mode of Python.
sys. argv stores a list of all command-line arguments provided to Python script. We know that the input ( ) function in a Python script is used to collect user inputs. However, inputs can also be given to the script from the command line. They are made available to the program in the form of this list object. For example:

E:\python37>python example.py aa bb

This is the command line to execute ‘example.py’ providing ‘aa’ and ‘bb’ as arguments. Three strings are stored in sys.argv list and can be accessed in the script. Name of script – sysexample.py in this case is stored at sys.argv. Other arguments are stored at successive indexes. Let sysexample.py script be as follows:

Example

#example.py
import sys
args=sys.argv
print ("Hello { }".format(sys.argv [ 1 ] ) )

It is now executed from the command line, (figure 3.3)

E:\python37>python sysexample.py Python
Hello Python
E:\python37>python sysexample.py Java
Hello Java

We are going to learn few more built-in modules and their functions in the following chapters:

• Serialization: CSV module,pickle module,dbmmodule,JSON module.
• DB-API: sqlite3 module, pymysql module, pyodbc module.

Function with Parameters

A parameter (also called an argument) is certain data passed on to the function while calling it. The previous section (sys module) showed how command-line arguments passed to a Python script can be processed by using sys. argv parameter. Similarly, one or more parameters can be passed to function from inside a script. Values of received parameters are then processed inside the function.

Two things must be kept in mind here. First, the function should be defined taking into consideration the number of parameters it is going to receive. Secondly, the function call should ensure it passes an adequate number of parameters as anticipated in the function’s definition. Variables used in function’s definition to receive passed values are often called formal arguments. Actual arguments are the values passed while calling.
In the following script, the LoveUO function is defined with one argument with a formal name as Hang’. Its value is used in the function to print relevant messages. User input is passed to this function as an actual argument.

Example

#function-2.py
def LoveU(lang):
'function with one parameter'
print ('I love { }'.format(lang))
return
#call above function
lang=input('enter name of a language..')
LoveU(lang)

Output:

E:\python37>python function-2.py
enter name of a language..Python
I love Python
E:\python3 7 >python function-2.py
enter name of a language..Hindi
I love Hindi

return Keyword

The return keyword at the end of the function block is merely to indicate that program flow would be returned to the calling position after the block is over. Use of return is optional in the sense program flow anyway goes back to calling position even if it is not used. However, if you intend to send some data back to the calling environment, then the return keyword must be used along with the expression to be returned.
Following script is a simple example of a function returning its result. It defines add () function to receive two numbers, perform addition, and return the result.

Example

#func-with-return.py
def add ( num1 , num2 ) :
'function assumes a two numbers to be passed'
result=num1+num2
return result
#call above function
x=int(input('enter a number..'))
y=int(input(1 enter another number.. '))
print ( ' addition of { } and { } is { } ' . format ( x , y , z ) )

Output

E:\python37>python func-with-return.py
enter a number..100
enter another number..200
addition of 100 and 200 is 300

Required Arguments

The statement that calls a function should pass exactly the same number of values as a number of actual arguments in its definition, otherwise, Python raises TypeError as in the following example, where the function is defined with two parameters but there is an attempt to call it with three values.

Example

#function-3.py
def LoveU( lang1 , lang2 ) :
'function with two parameters'
print ( ' I love { } and { } ' . format ( lang1 , lang2 ) )
return
#call above function
LoveU( 'Hindi ', ' Python ' , ' Java ' )

Output

E:\python37>python function-3.py
Tracebaok (most recent call last):
File "function-3.py", line 7, in <module>
LoveU('Hindi' , 'Python' , 'Java')
TypeError: LoveU( ) takes 2 positional arguments but
3 were given
E:\python37>

Values passed to a function are picked up by formal arguments in positional order. Since Python doesn’t enforce static typing, any formal argument may hold any type of data. However, there still may be errors raised inside a function if the treatment of the variable is not as per its value.

Look at the following script. The function in it receives two values. First, one is expected to be a string, and second a number. The function calculates the length of the string – the first parameter and determines if the number – second argument – is odd/even. Therefore, the function receives two values but with mismatching types, TypeError is raised when trying to compute len ( ) on a number data type.

Example

#function-4.py
def function(string,num):
'function assumes a string and number to be passed'
print ('length of string:', len(string))
if num%2==0:
print (num,' is 'even')
else:
print (num, ' is ','odd')
return
#call above function
function ('Hello', 10)
function (10, ’Hello')

Output

E:\python37>python function-4.pyOutput
length of string: 5
10 is even
Traceback (most recent call last) :
File "function-4.py", line 13, in <module>
function (10, 'Hello')
File "function-4.py", line 5, in function
print ('length of string:', lend string))
TypeError: object of type 'int' has no len( )

Parameter with Default Value

You can have a function that defines one or more parameters with default values. If the function call doesn’t explicitly give any value to the said parameter, the default will be used inside the function. If however, the call does pass a value, it will override the default settings in the function’s definition.

Example

#func-with-default.py
def dress(trouser, shirt='White'):
print ( 'Trouser is { }. Shirt is { }'.
format ( trouser , shirt ) )
dress( ' Black ' )
dress( ' Blue ' , ' Green ' )

You can see that the second argument is having a default value. The first call doesn’t give any value to it, so default is used. The second call overrides the default value. The output demonstrates this behavior (figure 3.9):

Trouser is Black. Shirt is White
Trouser is Blue. Shirt is Green

There is one precaution to be taken. Arguments with default values must appear after the required arguments in the parameter list of the function definition.

Function with Variable Arguments

We have already seen how arguments can be passed to Python script from the command line. All arguments are stored in a list object (sys. argv). On similar lines, if a function is called by passing the variable number of arguments from within the script, they are stored in a parameter prefixed with ‘*\ It is a list object of all values passed. Treat it as a normal list object and process it accordingly within the function. The following script is a very appropriate example of a function with variable parameters.

Example

#func-with-var-args.py
tt1 = 0
for num in nums:
tt1=tt1+num
return tt1
total=adda11 ( 10 , 20 , 50 , 70 )
print ( ' Total of 4 numbers: ' , total )
total=adda11 ( 11 , 34 , 43 )
print ( ' Total of 3 numbers : ' , total )

Output

E:\python37>python func-with-var-args.py
Total of 4 numbers: 150
Total of 3 numbers: 88