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 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.

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


enter n . . 5 
enter r . . 2 
C ( 5 , 2 ) = 10 . 0 
E:\python37 >python 
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.

#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 . . " ) )
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 aa bb

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

import sys
print ("Hello { }".format(sys.argv [ 1 ] ) )

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

E:\python37>python Python
Hello Python
E:\python37>python 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.

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


enter name of a language..Python 
I love Python 
E:\python3 7 >python 
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.

def add ( num1 , num2 ) :
'function assumes a two numbers to be passed'
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 ) )


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.

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


Tracebaok (most recent call last): 
File "", line 7, in <module> 
LoveU('Hindi' , 'Python' , 'Java') 
TypeError: LoveU( ) takes 2 positional arguments but 
3 were given 

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.

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


E:\python37>python function-4.pyOutput
parameter received Hello 10
length of string: 5
10 is even
parameter received 10 Hello
Traceback (most recent call last) :
File "", line 13, in <module>
function (10, 'Hello')
File "", 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.

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.

def addall(*nums):
tt1 = 0
for num in nums:
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 )


Total of 4 numbers: 150 
Total of 3 numbers: 88