Author name: Prasanna

Python Data Persistence – Decision Control

Python Data Persistence – Decision Control

Python’s if keyword constructs a conditional statement. It evaluates a boolean expression and executes an indented block of statements following it. The block is initiated by putting the Y symbol after the expression. (Indentation was already explained in the previous chapter.) The following skeleton shows typical usage of if statement and conditional block in a Python script:

Example

#using if statement
if expression==True:
#block of one or more statements
statement 1
statement 2
. . .
. . .
end of if block
#rest of the statements

Let us try to understand this with the help of a simple example. Following script computes tax on employee’s salary @10% if it is greater than or equal to 50,000. No tax is deducted if the salary is less than 50,000.

Example

# tax1 . py
salary= int (input("enter salary . . " ) )
tax=0
if salary>=50000:
#tax @10%
tax=salary*10/100
net_sal=salary-tax
print ("salary={ } tax= { } net payable= { }".
format (salary, tax , net_sal) )

 

Save the above script as ‘tax1.py’ and run it from the command prompt as shown below (figure 2.2):


C:\python37>python tax1.py 
enter salary..75000 
Salary=75000 tax=7500.0 net payable=67500.0 

C:\python37>python tax1.py 
enter salary..30000 
Salary=30000 tax=0 net payable=30000 

C:\python3 7 >

Python also provides else keywords. If there is another block of statements to be executed when the expression in if statement happens to be no True (False), it appears as:

Example

#using if statement
if expression==True:
#if block
statement 1
statement 2
. . .
. . .
#end of if block
else:
#else block
statement 1
statement 2
. . .
. . .
#end of else block
#rest of the statements

To show the use of else block, let us modify the previous example of computation of tax, assuming that tax is calculated 5% for salary<50000

Example

#tax2 . py
salary=int (input("enter salary . . " ) )
tax = 0
if salary>=50000:
# tax@10%
tax=salary*10/100
else:
#tax@5%
tax=salary*5/100
net_sal=salary-tax
print ("salary={ } tax={ } net payable = { }".
format (salary, tax, net_sal ) )

Two sample executions of the above script (tax2.py) are as shown below

C:\python37>python tax2.py
enter salary..60000
Salary=60000 tax=6000.0 net payable=54000.0
C:\python37 >python tax2.py
enter salary..20000
Salary=20000 tax=1000.0 net payable;=19000.0

C:\python3 7 >

Python also has elif keyword. Before using it in a Python script, let us modify the above tax calculation program to include few more tax slabs. The tax rate for salary above 50,000 is the same @10%. However, 5% tax is imposed for salary between 25,001 – 50,000. An employee with a salary between 10,001 – 25000 pays 2% tax, and anything below it requires no tax to be deducted. The script looks like as:

Example

#tax3 . py
salary=int ( input ( " enter salary . . " ) )
tax=0
if salary>=50000:
#tax @10%
tax=salary*10/100
else:
if salary>25000 :
#tax @5%
tax=salary*5/100
else:
if salary>10000:
#tax @2%
tax=salary*2/100
else:
#no tax
print ("No tax applicable")
net_sal=salary-tax
print ("Salary={ } tax={ } net payable={ }".
format(salary, tax, net_sal))

Here’s the output showing different tax slabs (figure 2.4)

C:\python37>python tax3.py 
enter salary..60000 
Salary=60000 tax=6000.0 net payable=54000.0 

C:\python37>python tax3.py 
enter salary..40000 
Salary=40000 tax=2000.0 net payable = 38000.0 

C:\python37>python tax3.py 
enter salary..18000 
Salary=18000 tax=360.0 net payable=17640.0 

C:\python37>python tax3.py 
enter salary..5000 
No tax applicable Salary=5000 tax=0 net payable=5000 

E:\python37>

 

While the output is satisfactory as per the expectations, the code (tax3. py) looks a little clumsy because of the increasing indent level of successive if blocks which fall in else part of the previous if statement. This is where the use of elif keyword provides a more elegant way to avoid these indentations and combine empty else with subsequent if block. The general syntax of if- elif- else usage is as shown below:

Example

#using elif statement
if exprl==True:
#first block
. . .
#end of the first block
elif expr2==True:
#second block executes if expr1 is False and expr2 is true.
. . .
#end of the second block
elif exp3==True:
#third block executes if expr2 is false and expr3 is true
. . .
#end of the third block
else:
#else block, executes if all preceding expressions are false
. . .
end of else block
#rest of the statements

In this structure, there is one if block, followed by one or more elif blocks and one else block at the end. Each subsequent elif is evaluated if the previous expression fails. The last else block is run only when all previous expressions turn out to be not true. Importantly all blocks have the same level of indentation. Here, is another version of tax3.py which uses elif blocks.

Example

#tax4.py
salary=int(input("enter salary.."))
tax=0
if salary>=50000:
#tax @10%
tax=salary*10/100
elif salary>25000:
#tax @5%
tax=salary*5/100
elif salary>10000:
#tax @2%
tax=salary*2/100
else :
#no tax
print ("No tax applicable")
net_sal=salary-tax
print ("Salary={ } tax={ } net payable={ }". format(salary, tax, net_sal))

The output of course will be similar to before.

Python Data Persistence – Decision Control Read More »

Python Data Persistence – for Keyword

Python Data Persistence – for Keyword

Like many other languages, Python also provides for keywords to construct a loop. However, Python’s for loop is a little different from others. Instead of a count-based looping mechanism, Python’s for loop iterates over each item in a collection object such as list, tuple, and so on.
Python’s sequence-type objects are the collections of items. These objects have an in-built iterator. An iterator is a stream that serves one object at a time until it is exhausted. Such objects are also called iterable. Python’s for loop processes one constituent of an iterable at a time till it is exhausted. The general form of usage of for statement is as follows:

Example

#using for loop
for obj in iterable:
#for block
#processing instructions of each object
. . .
end of block

Unlike the while loop, any other Boolean expression is not required to control the repetition of this block. Let us take a simple example. If you want to calculate the square of each number in a list, use for loop as shown below:

Example

#for-1.py
numbers=[4,7,2,5,8]
for num in numbers:
sqr=num*num
print ( ' sqaure of { } is { } ' . format ( num , sqr ) )

Output:

E:\python3 7 >python for-1.py 
square of 4 is 16 
square of 7 is 49 
square of 2 is 4 
square of 5 is 25 
square of 8 is 64 

E:\python37 >

Just as a list, a tuple or string object is also iterable. The following code snippet uses a for loop to traverse the characters in a sentence and count the number of words in it assuming that a single space (‘ ‘)separates them.

Example

#for-2.py
sentence=1 Simple is better than complex and Complex is. better than complicated. '
wordcount=1
for char in sentence:
if char==' ':
wordcount=wordcount+1
print ('the sentence has { } words'.
format(wordcount))

Output

E:\python37>python for-2.py 
the sentence has 11 words 

E:\python37>

Python Data Persistence – for Keyword Read More »

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
>>> dictl={'Mumbai':'Maharashtra', 'Hyderabad':'Telangana', 'Patna':'Bihar'}
>>> 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_')
enter your name: Ramkrishna
>>> 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
enter your name:Maya
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
enter your name : Mahesh
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

#area.py
length=int(input(‘enter length:1))
breadth=int(input(‘enter breadth:’))
area=length*breadth
print (‘area=1,area)

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

#area.py
length=int(input(‘enter length:’))
breadth=int (input(‘enter breadth:’))
area=length*breadth
print (‘length : ‘ , length, ‘breadth:’ , breadth, end=’ )
print(‘area=’ , area)

Output:

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

Python Data Persistence – Built-in Functions Read More »

Python Data Persistence – Installation

Python Data Persistence – Installation

Python’s official website hosts the official distribution of Python at https:// www.python.org/downloads/. Precompiled installers as well as source code tarballs for various operating system platforms (Windows, Linux, and Mac OS X) and hardware architectures (32 and 64-bit) are available for download. The bundle contains a Python interpreter and a library of more than 200 modules and packages.

Precompiled installers are fairly straightforward to use and recommended. Most distributions of Linux have Python included. Installation from source code is a little tricky and needs the expertise to use compiler tools.

Currently, there are two branches of Python software versions (Python 2.x and Python 3.x) on the Python website. At the time of writing, the latest versions in both branches are Python 2.7.15 and Python 3.7.2 respectively. Python Software Foundation (PSF) is scheduled to discontinue supporting the Python 2.x branch after 2019. Hence it is advised to install the latest available version of the Python 3.x branch.

It is also desirable to add Python’s installation directory to your system’s PATH environment variable. This will allow you to invoke Python from anywhere in the filesystem.

It is now time to start using Python. Open Windows Command Prompt terminal (or Linux terminal), type ‘python ’ in front of the prompt as shown below: (figure 1.1)

 

C:\Users\acer>Python
Python 3 . 7 . 2 (tags/v3 . 7 . 2 : 9a3ffc0492, Dec 23 2018,
23 : 09 : 28) [MSC v . 1916 64 bit (AMD64) ] on win32
Type "help", "copyright" , "credits" or "license" for more information.
>>>

If a Python prompt symbol »> (made up of three ‘greater than characters) appears, it means Python has been successfully installed on your computer.
Congratulations!!!

Most Python distributions are bundled with Python’s Integrated Development and Learning Environment (IDLE). It also presents an interactive shell as shown in Figure 1.1. Additionally, it also has a Python-aware text editor with syntax highlighting and smart indent features. It also has an integrated debugger.

python data presistance - Installation chapter 1 img 2

Interactive Mode

The >>> prompt means that Python is ready in REPL mode. You can now work with Python interactively. The prompt reads user input evaluates if it is a valid Python instruction, prints the result if it is valid or shows an error if invalid, and waits for input again. In this mode, the Python interpreter acts as a simple calculator. Just type any expression in front of the prompt and press Enter. Expression is evaluated with the usual meanings of arithmetic operators used and the result is displayed on the next line.

Example

>>> 5-6/2*3
-4.0
>>> (5-6/2)*3
6.0
>>>

You can assign a certain value to a variable by using the ‘=’ symbol. (What is variable? Don’t worry. I am explaining it also later in this chapter!) However, this assignment is not reflected in the next line before the prompt. The assigned variable can be used in further operations. To display the value of a variable, just type its name and press Enter.Python operators follow the BODMAS order of precedence. There are few more arithmetic operators defined in Python. You will learn about them later in this chapter.

Example

>>> length=20
>>> breadth=30
>>> area=length*breadth
>>> area
600

Scripting ModeType ‘quit( )’ before the prompt to return to the command prompt.

Interactive mode as described above executes one instruction at a time. However, it may not be useful when you have a series of statements to be repetitively executed. This is where Python’s scripting mode is used. The script is a series of statements saved as a file with the ‘.py’ extension. All statements in the script are evaluated and executed one by one, in the same sequence in which they are written.

The script is assembled by using any text editor utility such as Notepad (or similar software on other operating systems). Start Notepad on Windows computer, enter the following lines and save as ‘area.py’

Example

#area.py
length=20
breadth=30
area=length*breadth
print (1area=',area)

Open the command prompt. Ensure that the current directory is the same in which the ‘area.py’ script (you can call it a program) is saved. To run the script, enter the following command (figure 1.2):

C : \ Users \ acer>Python area . py
area = 600

Comments

Any text that follows the ‘#’ symbol is ignored by the Python interpreter. This feature can be effectively used to insert explanatory comments in the program code. They prove to be very useful while debugging and modifying the code. If a symbol appears in a line after a valid Python statement, the rest of the line is treated as a comment.

Example

>>> #this line is a comment
... print ("Hello world!")
Hello, world!
>>> print ("hello world again!") #this also a comment
hello, the world again!

Multiple lines of text which are enclosed within triple quote marks are similar to comments. Such text is called ‘docstring’ and appears in the definition of the function, module, and class. You will come across docstrings when we discuss these features in subsequent chapters.

Python Data Persistence – Getting Started

Python Data Persistence – Program Flow Control

Python Data Persistence – Installation Read More »

Python Data Persistence – User Defined Functions

Python Data Persistence – User Defined Functions

As mentioned earlier, it is possible to define a custom function if you don’t find a suitable one in the collection of predefined functions. It is popularly called a user-defined function. So, let us proceed to define a new function and learn how to use it.
Python provides a def keyword for this purpose. This keyword is followed by a suitable identifier and in front of which give parentheses. The parentheses may or may not have anything inside. This is followed by a function block of one or more statements of uniform indent level. A formal outline of function definition appears like this:

Example

#defining a function
def function ( [ p1 , p2 , . . ] ) :
' function docstring as first-line in function block'
. .
. .
return [value]

Subsequent lines can have any number of valid Python statements as demanded by the function’s processing logic. The last statement of the block should be returned indicating that the program’s control is going back to the position from where this function was called. You may put an expression in its front if it is required that this function should not just return but return with a value (most of the time, result of the function).As always you’ll use the symbol to start a block. You may write a string literal as an explanatory string for the function. It is called docstring and is optional. Something similar to comment but is treated as the value of function’s _doc_ attribute.

How should this user-defined function be called? Just use its name as a Python statement anywhere in the code after it has been defined. Of course, you need to provide adequate parameters if the function’s definition contains any.
So, let us define a function with the name ‘zen’ and no parameters. When called, it will print a couple of lines from ‘Zen of Python’ – a set of guiding principles that govern the design philosophy of Python.

Example

#function-1.py
def zen( ):
' Zen of Python '
print ( ' Beautiful is better than ugly. Explicit is better than implicit.')
print ('Simple is better than complex. Complex is better than complicated.')
return
#call above function
zen ( )
print ('Docstring:', zen. _doc_ )

Output:

E:\python37>python function-1.py 
Beautiful is better than ugly. Explicit is better than implicit. 
Simple is better than complex. The complex is better than the complicated. 
Docstring: Zen of Python

Note that docstring – the first line in function block is not executed by interpreter but is recognized as the value of doc attribute.

Python Data Persistence – User Defined Functions Read More »

Python Data Persistence – Keyword Arguments

Python Data Persistence – Keyword Arguments

We now know that the values passed to a function are read as per the order in which parameters are defined. However, if you do want to pass values out of order, use the parameter’s name as keyword. Following code snippet will illustrate the point:

Example

#func-with-keywords.py
def division(num, denom):
div=num/denom
print ('numerator: { } denominator: { } division: { } ' . format ( num , denom , div ) )
division ( 10 , 2 )
division ( 2 , 10 )
division(denom=2, num=10)

In the first two cases, the first argument becomes numerator, and the second becomes denominator as values are picked up by formal parameter names as per the order. In the last case, the name of the parameter is used as a keyword so that even if values are passed out of order, they go in desired parameters of the function.

Output:

E:\python3 7>python func-with-keywords.py 
numerator:10 denominator: 2 division: 5.0 
numerator:2 denominator: 10 division: 0.2 
numerator:10 denominator: 2 division: 5.0

Note that in the above example, the use of keyword arguments is optional. To force compulsory use of keyword arguments, use as one parameter in the parameter list. All parameters after * become keyword-only parameters. Any parameters before * continue to be positional parameters.

The above example is modified so that both parameters are made keyword-only by putting * as the first parameter in the list. Now if you try to call the division( ) function without specifying keywords, TypeError is raised.

Example

#func-with-kwonly.py
def division( * , num , denom ) :
div=num/denom
print ('numerator:{ } denominator: { } division: { } ' . format(num , denom , div ) )
division(denom=2, num=10)
division(10,2)

Output

E:\Python37>Python func-with-kwonly.py
numerator:10 denominator: 2 division: 5.0 
Traceback (most recent call last): 
File "func-with-kwonly.py", line 7, in <module> division(10,2) 
TypeError: division( ) takes 0 positional arguments but 2 were given

Python uses the mechanism of keyword arguments and arguments with default value very extensively in defining built-in functions and methods. One such example is int ( ) function. In fact, we had discussed int() function in chapter 1. It can be used as per two prototype definitions:

int([x])
 int(x, base=10)

In the first definition, the parameter x should be a number. The function returns its integer part. In the second case, x must be a string containing digits only. The second parameter – base has a default value of 10. But it can be 2, 8, 16, and so on. i.e. base of binary, octal, or hexadecimal number system. The string is then converted to a number accordingly. The base parameter can be used like a normal positional argument or keyword argument.

Example

>>> #converts float to int
>>> int ( 123 . 45 )
123
>>> #converts string to number with default base 10 - decimal number system
. . .
>>> int('121')
121
>>> #converts string with hexadecimal digits - base=16 as positional argument
. . .
>>> int('121',16)
289
>>> #converts string with hexadecimal digits - base=16 as keyword argument
. . .
>>> int('121',base=16)
289

Python Data Persistence – Keyword Arguments Read More »

Python Data Persistence – Package

Python Data Persistence – Package

The concept of the package takes Python’s modular approach to next level. A package is a collection of modules. All modules having the functionality of certain common features are stored in one folder. Python’s standard library contains some packages that are collections of modules. For example, the Tkinter package, which is Python’s implementation of the TCL/Tk UI toolkit, consists of several modules such as Tkinter. ttk, Tkinter.messagebox, tkinter.commondialog, and so on. The importlib is another Python package in the standard library that has multiple modules (importlib. ABC, importlib. util, importlib. machinery, and so on.) You can build your own package having multiple but related modules under one folder. Let us see how it can be done.

In addition to Python modules, the folder should have a special file named as__init__.py for it to be recognized as a package by the Python interpreter. This file is also useful to build a packaging list of functions from various modules under the folder.
So, let us build a package named ‘MyPackage’. First of all, create a new folder at some suitable location in a filesystem (for example c:\testpackage) and a subfolder under it. Name the subfolder as ‘MyPackage’. Go on to save the following module scripts in it.

Example

#addfunctions.py
def add ( num1 , num2 ) :
result=num1 + num2
return result
def adda11(*nums) :
tt1 = 0
for num in nums:
tt1=tt1+num
return tt1
#mathfunctions.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
#myfunctions.py
def isprime(num):
x=2
for x in range(2,num):
if num%x==0:
return False
else:
return True
def'iseven(num):
if num%2==0:
return True
else:
return False
def isleap(num):
if num%4==0:
return True
else:
return False

In addition to above, create an empty__init__. py in My package folder. The folder structure should appear as shown below (figure 3.17) :

C:\TestPackage 
| example.py 
| 
|_ __ _MyPackage 
addtunctions.py 
mathfunctions.py 
myfunctions.py 
__init___.py

Next, open the command prompt window while in the TestPackage directory and start Python. The child directory in it, MyPackage is recognized as a legitimate Python package because it does contain__init__.py, so you can import any module available in it. The usage is shown below:

C:\TestPackage>
python >>>

Example

>>> from MyPackage import add functions
>>> add functions.adda11(1,2,3,4)
10
>>> from MyPackage import functions
>>> functions . is prime (67)
True
>>> from MyPackage import math functions
>>> math functions.power(10,2)
100

What is more, it is possible to require a function by name from any module.

Example

>>> from MyPackage.math functions import power,
average
>>> power ( 5 , 4 )
625
>>> average ( 20 , 30 )
25.0

This is where__init__. py file plays an important role. It can provide package-level access to certain functions chosen from various modules. Let us modify the __init__. py script as shown below:

Example

#__init__.py
from. mathfunctions import average
from. addfunctions import adda11
from. myfunctions import isprime, iseven

Now, what does this__init__.py script do? It allows a function to be accessed by name of a package and not by name of a module which originally defined. To verify this behavior, save the following script as ‘example.py’ in the parent folder (‘testpackage’)

Example

#example.py
import MyPackage
ffcalling isprime function
num=int ( input ( 1 enter a number . . ' ) )
retval=MyPackage . isprime ( num )
if retval==True:
print ( " { } is a prime number " . format ( num ) )
else:
print ( " { } is not a prime number " . format ( num) )
#adda11 function
result=MyPackage.adda11( 10 , 20 )
print ( " Result of addition : " , result )

Output

C:\TestPackage>python 
example.py enter a number..23 
23 is a prime number 
Result of addition: 30

In the above discussion, we learned how to create a package and use it from inside its parent folder. It is also possible to install the package for system-wide use. However, this book’s scope doesn’t cover its explanation. At this juncture, it is sufficient to state that it can be achieved by using a setup tools module from Python’s standard library. You can also upload your package to the Python Package Index repository (https://pypi.org//). The procedure is explained in detail on the website itself.
However, it is important to know how to install a new package in your computer’s Python library. The latest versions of Python come with pip utility.

Python Data Persistence – Package Read More »

Python Data Persistence – User Defined Modules

Python Data Persistence – User Defined Modules

A module is a collection of Python objects such as functions, classes, and so on. Python interpreter is bundled with a standard library consisting of a large number of built-in modules, some of which we got acquainted with. Just as built-in modules, you can create a collection of your own functions and import them in an interactive Python session or in another script.

Any Python script (having .py extension) can be used as a module. The idea behind a user-defined module is the same as that of a built-in module. If the entire programming solution involves quite a large number of functions and classes, in that case putting all definitions in a single script is likely to be troublesome. A better way is to organize them in separate modules. Functions and classes of similar relevance are kept in one module. Such an approach makes the code easier to maintain. First of all, let us put some functions in a script called ‘mymodule.py

Example

‘docstring of mymodule’
def isprime(num):
x=2
for x in range(2,num):
if num%x==0:
return False
else:
return True
def iseven(num):
if num%2==0:
return True
else:
return False
def isleap(num):
if num%4==0:
return True
else:
return False

We can now import any function from this module in an interactive interpreter session, just as we imported the math module.

Example

>>> import mymodule
>>> mymodule . isprime ( 43 )
True
>>> mymodule . isprime ( 72 )
False
>>> mymodule . iseven ( 28 )
True
>>> mymodule . iseven ( 93 )
False
>>> mymodule . isleap (2019)
False
>>> mymodule . isleap ( 1996 )
True
>>>

It is also possible to import this module in another Python script. Here is an example script ‘moduledemo.py’

Example

#moduledemo.py
import mymodule
print (‘calling isprime function from mymodule1)
n=int(input(‘enter a number..’))
retval=mymodule.isprime(n)
if retval==True:
print ( ‘ { } is a prime number ‘ . format ( n ) )
else:
print ( ‘ { } is not a prime number ‘ . format ( n ) )

Output

E:\python37>python moduledemo.py
calling isprime function from mymodule
enter a number . . 39
39 is not a prime number
E:\python37>python moduledemo.py
calling isprime function from mymodule
enter a number . . 97
97 is a prime number

_name_ attribute
As is often said, everything in Python is an object. Likewise, a module – whether built-in or user-defined – is also an object of module class.

Example

>>> #module object – built-in module
. . .
>>> import math
>>> type(math)
<class ‘module’>
>>> #module object – user defined module
. . .
>>> import mymodule
>>> type(mymodule)
<class ‘module’>

Module object is characterized by various attributes. One of the important attributes of a module object is__name___and it has a peculiar behavior. Inside Python’s interactive shell, the__name__attribute returns ‘__main__’. It is the name of the top-level namespace in which the Python interpreter is running. However, the value of an imported module’s__name__ attribute is the name of the module itself (excluding the .py part from the script’s name)

Example

>>> #__name__ attribute of interactive shell
. . .
>>>__name__
‘__main__’
>>> #__name__ attrbute of imported module
. . .
>>> import math
>>> math.__name__
‘ math’
>>> import mymodule
>>> ‘mymodule.__name__
‘mymodule’

This is also the same in the case of a Python script. When a certain script is run from the command line, Python is running in scripting mode. Hence value of__name__in the script is ‘__main__’. So also,__name__attribute of a module imported in the script is its name itself. Run the following code from the command line.

Example

#moduledemo-1.py
import mymodule
print (‘_name_ of top level module: ‘ ,__name__)
print (‘__name__ of imported mymodule : ‘ , mymodule.__name__)

Output

E:\python37>python moduledemo-1.py
__name__of top level module:__main__
__name__ of imported mymodule: mymodule

A script having function definitions may also have certain executable code also in it. What happens if it is imported into another script? Let us see. Open mymodule.py and add statements that call is even( ) function after definitions.

Example

‘docstring of mymodule’
def isprime(num):
x=2
for x in range(2,num):
if num%x==0:
return False
else:
return True
def iseven(num):
if num%2==0:
return True
else:
return False
def isleap(num):
if num%4==0:
return True
else:
return False
##add following statements
n=int(input(‘enter a number..’))
retval=iseven(n)
if retval==True:
print ( ‘ { } is even ‘ . format ( n ) )
else:
print ( ‘ { } is odd ‘ . format ( n ) )

Now if the moduledemo.py is run (it imports my module in it). Look at the result, (figure 3.15)

E:\python37>python moduledemo.py
enter a number..23
23 is odd
calling is prime function from my module
enter a number23
23 is a prime number

You find that the executable part in the imported module also runs. Obviously, we don’t want this to happen. We do want the executable code to run when the module script is invoked but not when it is imported. The peculiar behavior of__name__attribute comes in handy here. As we saw, its value happens to be ‘__main__’ when a module script is run, but__name__attribute takes up its name when imported. So we have to test this attribute and run the executable code only if it is ‘__main__’. Modify the my module code as follows:

Example

‘docstring of mymodule’
def isprime(num):
x=2
for x in range(2,num):
if num%x==0:
return False
else:
return True
def iseven(num):
if num%2==0:
return True
else:
return False
def isleap(num):
if num%4==0:
return True
else:
return False
#modify as follows:
if __name__==’__main__’ :
n=int ( input ( ‘ enter a number . . ‘ ) )
retval=iseven(n)
if retval==True:
print ( ‘ { } is even ‘ . format ( n ) )
else:
print ( ‘ { } is odd ‘ . format ( n ) )

You can run mymodule.py independently but wouldn’t affect the execution of moduledemo.py. (figure 3.16)

E:\python37>python moduledemo.py
calling is a prime function from my module
enter a number..11
11 is a prime number

 

Python Data Persistence – User Defined Modules Read More »

Python Data Persistence – Math Module

Python Data Persistence – Math Module

As you would expect, the math built-in module is one of the most frequently used. Various functions which are often required are defined in this module. Functions for computing all trigonometric ratios are present in the math module. All these functions calculate the respective ratio of an angle given in radians. Knowing that 30 degrees are roughly equal to 0.5236, various ratios are calculated as follows:

Example

>>> import math
>>> math.sin(0.5236)
0.5000010603626028
>>> math.cos(0.5236)
0.866024791582939
>>> math.tan(0.5236)
0.5773519017263813
>>>

The math module also has two functions to convert the measure of an angle in degrees to radians and vice versa.

Example

>>> math.radians(30)
0.5235987755982988
>>> math.degrees(0.52398)
30.021842549264875
>>>

Two important mathematical constants are defined in this module. They are Pie (π) and Euler’s number (e)

Example

>>> math.e
2.718281828459045
>>> math.pi
3.141592653589793
>>>

We have used sqrt ( ) function from math module. Likewise the module has pow ( ) , log ( ) , and exp ( ) functions.

Example

>>> math . sqrt ( 25 )
5.0
>>> math . pow ( 5 , 2 )
25.0
>>> math.log(10) #natural logarithm using math.e as base
2.302585092994046
>>> math.loglO(100) ttstandard logarithm using 10 as base
2.0
>>>

The mod operator (%) and floor operator (//) were introduced earlier. This module contains similar functions ( remainder ( ) and floor ( ) ). Another ceil( ) function in this module returns the nearest integer of a division operation.

Example

>>> math.remainder(10,6) #Difference between numerator and closest integer multiple of denominator
-2.0
>>> math.floor(10/6) #Returns the largest integer < = given float
1
>>> math.ceil(10/6) #Returns the smallest integer >= float
2
>>>

 

Python Data Persistence – Math Module Read More »

Python Data Persistence – Function

Python Data Persistence – Function

The function is called a structured approach to program development. Idea is to break the algorithm into one or smaller, independent, and reusable blocks of instructions. Each such block, designed to perform a single task is known as a function. It is called wherever it is required in the main routine of the program. When called, each function performs the process as defined in it and returns the control back to the main routine, (figure 3.2)

IMG

Thus the function is an important building block of any software. Python interpreter itself has quite a few in-built functions. You have already come across some of them. In addition, standard Python installation a library of many built-in modules (nearly 500 modules are bundled in standard Python distribution), each one having some functions defined in it. While built-in functions are always available, functions in other built-in modules have to be explicitly loaded. Remember we used a randint () function to generate a random integer as a secret number in the previous chapter (secret-number.py). Let us look at another function that calculates the square root of a number. The sqrt () function is defined in the math module. (The math module itself contains nearly 50 functions.) You need to import this module for that purpose.

Example

>>> import math
>>> math.sqrt(100)
10.0
>>>

As you can see, the Python interpreter has access to a large number of predefined functions, either built-in or built-in modules. You can employ these functions in your program as per requirement. You can of course develop your own function if you don’t find a suitable function in any of the built-in modules. These built-in modules are appropriately named to indicate the type of functions in them. Examples are math module (having mathematical functions) and random module (having random number generation functions).

Built-in modules are generally written in C and bundled with Python interpreter in precompiled form. A built-in module may be a Python script (with .py extension) containing useful utilities. A module may contain one or more functions, classes, variables, constants, or any other Python resources.

To display a list of all available modules, use the following command in the Python console:

>>> help(‘modules’)

Python has an import keyword to load all contents of a module in the current namespace of the Python interpreter. Functions can then be called using dot operator as follows:

Example

import module
module.function ( [ arguments if any ] )

Python also provides from keyword that allows only specified functions from a module rather than all functions. The sqrt () function from the math module can also be imported as follows:

Example

>>> from math import sqrt
>>> sqrt(100)
10.0
>>>

We shall first get ourselves acquainted with some of the frequently required functions in built-in modules before we learn how to define and use our own functions.

Python Data Persistence – Function Read More »