Author name: Prasanna

Python Programming – Class

In this Page, We are Providing Python Programming – Class. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class

Class

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embodies the attributes: the “data attributes” and “methods”, specific to a data type. A class definition is given below:

classdef        : := " class " classname [ inheritance ] " : " suite
inheritance   : := " ( " [ expression_list ] " ) " 
classname    : := identifier

The above class definition might seem alien, it will become more clear with the progress of this Chapter. The simplest form of class definition looks like:

class ClassName: 
        <statement-1>
         .
 
        .

       .
      <statement-N>

The following example gives a glimpse of how a class is defined.

>>> class Output :
. . .      def Display ( self ) :
. . .            print ' This is a class example . '
. . . 
>>> x=Output ( ) 
>>> x . Display ( )
This is a class example.

Like function definition (def statements), the class definition (Output in the above example) must be executed before they have any effect. In practice, the statements inside a class definition will usually be function (or more specifically “method”) definitions (Display ( ) in the above example), but other statements are allowed. The function definitions inside a class normally have a peculiar form of the argument list, dictated by the calling conventions for methods (discussed later).

The creation of a class definition also creates a new namespace, and used as the local scope, thus all assignments to local variables go into this new namespace.

Python Programming – Class Read More »

Python Programming – Constants

In this Page, We are Providing Python Programming – Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Constants

Constants

math.pi
The mathematical constant π.

math. e
The mathematical constant e.

>>> math.e
2.718281828459045

Number-theoretic and representation functions

math . ceil ( x )
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.

>>> import math 
>>> math . ceil ( -3 . 2 )
-3 . 0
>>> math . ceil ( 3 . 2 )
4 . 0

math . copysign ( x , y )
Return x with the sign of y.

>>> math . copysign ( 5 . 1 , -2 . 8 )
-5 . 1
>>> math . copysign ( -5 . 1 , 2 . 8 )
5 . 1

math . tabs ( x )
Return the absolute value of x.

>>> math . fabs ( - 4 . 2 )
4 . 2

math . factorial ( x )
Return x factorial. Raises ValueError, if x is not integral or is negative.

>>> math . factorial ( 5 ) 
120 
>>> math . factorial ( -5 ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
ValueError: factorial ( ) not defined for negative values

math . floor ( x )
Return the largest integer value less than or equal to x as a float.

>>> math . floor ( -3 . 2 )
-4 . 0
>>> math . floor ( 3 . 2 )
3 . 0

math . fmod ( x , y )
Return remainder of a division expression. Note that the Python expression x%y may not return the same result. The result of fmod (x, y) has same sign as x, while x%y returns a result with the sign of y instead.

>>> math . fmod ( 5 . 0 , -2 . 0 )
1 . 0
>>> 5 . 0% -2 . 0 
-1 . 0
>>> math . fmod ( -5 . 0 , 2 . 0 )
-1 . 0
>>> -5 . 0 % 2 . 0
1 . 0

Consider the following interesting scenario.

>>> math . fmod ( -1e-100 , 1e100)
-1e-100 
>>> -1e-100 % 1e100
1e +100

It can be observed that fmod (-1e-100 , 1e100) returns -1e-100, but the result of Python’s – 1e-100%1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod ( ) is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math . frexp ( x )
Return the mantissa and exponent of x as the pair (m, e). The m is a float and e is an integer such that x = m x 2e exactly. If x is zero, returns ( 0 . 0 , 0 ) , otherwise 0 . 5<=abs ( m ) <1.

>>> math . frexp ( 4 . 0 )
( 0 . 5 , 3 )
>>> 0 . 5*2**3
4 . 0
>>> math . frexp ( 0 . 1 )
( 0 . 8 , -3 )
>>> 0 . 8* 2**-3
0 . 1
>>> math . frexp ( -4 . 0 )
( -0 . 5 , 3 )
>>> -0 . 5*2**3
- 4 . 0

math.fsum(iterable)
Return an accurate floating point sum of values in the iterable.

>>> math . fsum ( [ . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 ] )
1 . 0

math . isinf ( x )
Check if the float x is positive or negative infinity.

>>> a=1e+300
>>> a
1e+300
>>> math . isinf ( 1e+300 )
False
>>> a=1e+310
>>> a
inf
>>> math . isinf ( 1e+310 )
True

Calculating an exponent with floating point values, in particular, raises Overf lowError instead of preserving the inf result.

>>> a=10 . 0**310

Traceback ( most recent call last ) :
File "<pyshell#l>", line 1, in <module>
    a=10 . 0**310
OverflowError: (34 , ' Result too large ' )

math . isnan ( x )
Check if the float x is a nan (not a number), nan does not compare as equal to any value, even itself, so nan should be checked using isnan () function.

>>> a=1e+310
>>> a
inf
>>> b=a/a
>>> b
nan
>>> math . isnan ( a )
False
>>> math . isnan ( b )
True

math . ldexp ( x , i )
Return x* (2**i). This function is reverse of function frexp ( ).

>>> math . 1dexp ( -0 . 5 , 3 )
-4 . 0
>>> -0 . 5*2**3
-4 . 0
>>> math . ldexp ( 0 . 8 , -3 )
0 . 1
>>> 0 . 8*2**-3
0 . 1

math . modf ( x )
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

>>> math . modf ( 1 . 5 )
( 0 . 5 , 1 . 0 )

>>> math . modf ( -1 . 5 )
( -0 . 5 , -1 . 0 )

math . trunc ( x )
Return the real value x truncated to an integer.

>>> math . trunc ( 93 . 2508 )
93
>>> math . trunc ( -93 . 2508 )
-93

Power and logarithmic functions

math . exp ( x )
Return ex.

>>> math . e**-3 . 2
0 . 04076220397836622
>>> math . pow ( math . e , -3 . 2 )
0 . 04076220397836622
>>> math . exp ( -3 . 2 )
0 . 04076220397836621

math . expm1 ( x )
Return ex-1. For small floats x, the subtraction in exp(x)-1 can result in a significant loss of precision; the expml ( ) function provides a way to compute this quantity to full precision:

>>> x=0 . 0000000000000000000000001
>>> math . exp ( x ) , -1
0 . 0
>>> math . expm1 ( x )
1e - 25

math . log ( x [ , base ] )
With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log (x) / log (base).

>>> math . log ( 9 )
2 . 1972245773362196
>>> math . log ( 9 , 2 )
3 . 1699250014423126

math . loglp ( x )
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

>>>x=0.0000000000000000000000001
>>> X
1e-25
>>> 1+x
1 . 0
>>> math . 1og ( 1 +x )
0 . 0
>>> math . 1og1p ( x )
1e-25

math . 1og10 ( x )
Return the base-10 logarithm of x. This is usually more accurate than log (x, 10).

>>> math . 1og10 ( 100 )
2 . 0
>>> math . 1og10 ( 10000 )
4 . 0

math . pow ( x , y )
Return x raised to the power y. In particular, pow ( 1 . 0 , x ) and pow ( x , 0 . 0 ) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow (x, y) is undefined, and raises ValueError.

>>> math.pow ( 9 . 0 , 0 . 5 )
3 . 0
>>> math . pow ( -9 . 0 , 0 . 5 )
Traceback ( most recent call last ) :
File "<stdin>" , line 1 , in <module>
ValueError: math domain error

Unlike the built-in * * operator, math. pow ( ) converts both its arguments to type float.

math . sqrt( x )
Return the square root of x. Computing the square roots of negative numbers requires complex numbers, which are not handled by math module. Any attempt to calculate a square root of a negative value results in ValueError.

>>> math . sqrt ( 9 . 0 )
3 . 0
>>> math . sqrt ( -9 , 0 )

Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
math . sqrt ( -9 . 0 )
ValueError: math domain error

Trigonometric functions

math . acos ( x )
Return the arc cosine of x, in radians.

>>> math . acos ( 0 . 5 )
1 . 0471975511965979

math . asin ( x )
Return the arc sine of x, in radians.

>>> math . asin ( 0 . 5 )
0 . 5235987755982989

math . atan ( x )
Return the arc tangent of x, in radians.

>>> math . atan ( 0 . 5 )
0 . 4636476090008061

math . atan2 ( y , x )
Return atan(y/x), in radians. The resuit is between -TI and TI. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2 () is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan (1) and atan2 (1,1) are both n /4, but atan2 (-1,-1) is -3#/4.

>>> math . atan ( 1 . 0 )
0 . 7853981633974483
>>> math . pi / 4
0 . 7853981633974483

math . cos ( x )
Return the cosine of x radians.

>>> math . cos ( 0 . 7853981633974483 )
0 . 7071067811865476

math . hypot ( x , y )
Return the Euclidean distance, \(\sqrt{x^{2}+y^{2}}\) . This is the length of the vector from the origin to point (x,y).

>>> math . hypot ( 3 . 0 , 4 . 0 )
5 . 0

math . sin ( x )
Return the sine of x radians.

>>> math . sin ( 0 . 7853981633974483 )
0 . 7071067811865475

math . tan ( x )
Return the tangent of x radians.

>>> math.tan ( 0 . 7853981633974483 )
0.9999999999999999

Angular conversion

math . degrees ( x )
Converts angle x from radians to degrees.

>>> math . degrees ( 1 . 5707963267948966 )
90 . 0
>>> 1 . 5707963267948966*180 / math . pi
90 . 0

math . radians ( x )
Converts angle x from degrees to radians.

>>> math . radians ( 90 )
1 . 5707963267948966
>>> ( 90*math . pi ) / 180
1 . 5707963267948966

Hyperbolic functions

math . acosh ( x )
Return the inverse hyperbolic cosine of x.

>>> math . cosh ( 1 . 0 )
1 . 5430806348152437

math . asinh ( x )
Return the inverse hyperbolic sine of x.

>>> math . asinh ( 1 . 0 )
0 . 8813735870195429

math . atanh ( x )
Return the inverse hyperbolic tangent of x.

>>> math . atanh ( 0 . 8 )
1 . 0986122886681098

math . cosh ( x )
Return the hyperbolic cosine of x.

>>> math . cosh ( 0 . 7853981633974483 )
1 . 3246090892520057

math . sinh ( x )
Return the hyperbolic sine of x.

>>> math . sinh ( 0 . 7853981633974483)
0 . 8686709614860095

math . tanh ( x )
Return the hyperbolic tangent of x.

>>> math . tanh ( 0 . 7853981633974483 )
0 . 6557942026326724

Special functions

math . erf ( x )
Return the error function at x.

>>> math . erf ( 0 . 25 )
0 . 2763263901682369

math . erfc ( x )
Return the complementary error function at x i.e. 1-erf (x).

>>> math . erf c ( 0 . 25 )
0 . 7236736098317631

math . gamma ( x )
Return the gamma function at x.

>>> math . gamma ( 5 . 5 )
52 . 34277778455352

math . lgamma ( x )
Return the natural logarithm of the absolute value of the gamma function at x.

>>> math . 1 gamma ( 5 . 5 )
3 . 9578139676187165

Python Programming – Constants Read More »

Python Programming – Looping Techniques

In this Page, We are Providing Python Programming – Looping Techniques. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Looping Techniques

Looping techniques

The list can also be used in iteration operation, for example:

>>> for a in [ 4 , 6 , 9 , 2 ] : print a
4
6
9
2
>>> for a in [ 4 , 6 , 9 , 2 ] : print a ,
. . .
4 6 9 2

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate ( ) function.

>>> for i ,v in enumerate ( [ ' tic ' , ' tac ' , ' toe ' ] ) :
. . . print i, v
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip () function.

>>> questions= [ ' namer , ' quest ' , ' favorite color ' ]
>>> answers= [ ' lancelot ' , ' the holy grailblue ' ] 
>>> for q,a in zip ( questions , answers ) :
. . .   print 'What is your { 0 } ? It is { 1 }.'. format ( q , a) 
What is your name ? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

While iterating a mutable sequence, if there is a need to change the sequence (for example to duplicate certain items), it is recommended to make a copy of the sequence before starting iteration. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient.

>>> words= [ ' cat ' , ' window ' , ' defenestrate ' ]
>>> for w in words [ : ] :
. . . if len ( w )>6:
. . . words. insert ( 0 , w )
>>> words
[ ' defenestrate ' , ' cat ' , ' window ' , ' defenestrate ' ]

Nested list

It is possible to nest lists (create list containing other lists), for example:

>>> q= [ 2 , 3 ]
>>> p= [ 1 , q , 4 ]
>>> len ( p )
3
>>> p [ 1 ]
[ 2 , 3 ]
>>> p [ 1 ] [ 0 ]
2
>>> p [ 1 ] . append ( ' xtra ' )
>>> p
[ 1 , [ 2 , 3 , ' xtra ' ] , 4 ]
>>> q
[ 2 , 3 , ' xtra ' ]

Note that in the last example, p [ 1 ] and q refer to the same object, which can be cross-checked using the id ( ) built-in function.

>>> id ( q )
104386192
>>> id (p [1] )
104386192

Python Programming – Looping Techniques Read More »

Python Programming – Deleting List Elements

In this Page, We are Providing Python Programming – Deleting List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Deleting List Elements

Deleting list elements

To remove a list element, one can use either the del statement (if you know the element index to delete) or remove () method (if you do not know the element index, but the element itself, discussed in section 4.1.9). The following example depicts the deletion of an element using the del statement.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ]
>>> a
[ ' spam ' , 100 , 1234 ]

The del statement can also be used to explicitly remove the entire list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a 
>>> a
Traceback ( most recent call last ) :
File " <stdin> " , line 1 , in <module>
NameError: name ' a ' is not defined

The following is an interesting case of the del statement:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ] , a [ 1 ]
>>> a
[ ' spam ' , 1234 ]

It should be noted that the same index is deleted twice. As soon as an element is deleted, the indices of succeeding elements are changed. So deleting an index element n times, would actually delete n elements.

It is also possible to delete multiple items from a list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 3 ] = [ ]
>>> a
[ ' spam ' , 1234 ]

Swapping lists

There might be a scenario in which multiple lists need to be swapped among themselves. This is can done easily using multiple assignments expression.

>>> a= [ 10 , 20 , 30 ] 
>>> b= [ 40 , 50 , 60 ] 
>>> c= [ 70 , 80 , 90 ]
>>> a , b , c=c , a , b 
>>> a
[ 70 , 80 , 90 ] 
>>> b
[ 10 , 20 , 30 ]
>>> c
[ 40 , 50 , 60 ]

Python Programming – Deleting List Elements Read More »

Python Programming – Updating List Elements

In this Page, We are Providing Python Programming – Updating List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Updating List Elements

Updating list elements

It is possible to change individual or multiple elements of a list:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 0 ]= ' filter '
>>> a
[ ' filter ' , ' eggs ' , 100 , 1234 ]
>>> a [ 2 : 4 ]= 455 , 56858 
>>> a
[ ' filter ' , ' eggs ' , 455 , 56858 ]

The items of list can be updated by the elements of another iterable (list, tuple).

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b=[ ' hi ' , ' bye ' ]
>>> a [ 2 : 4 ] =b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= ( ' hi ' , ' bye ' )
>>> a [ 2 : 4 ]=b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= [ ' hi ' , ' bye ' ] 
>>> a [ 1: 4 : 2 ] =b 
>>> a
[ 66 . 25 , ' hi ' , 333 , ' bye ' , 1234 . 5 ]

It is also possible to insert elements in a list.

>>> a=[ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ]=[ ' chair ' ]
>>> a
[ ' spam ' , ' chair ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ] = [ ' hello ', ' bye ' ]
>>> a
[ ' spam ' , ' hello ' , ' bye ' , ' chair ' , ' eggs ' , 100 , 1234 ]

To insert a copy of the list at the beginning of itself:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ : 0 ]=a 
>>> a
[ ' spam ' , ' eggs ' , 100 , 1234 , ' spam ' , ' eggs ' , 100 , 1234 ]

There are various methods of list objects for updating the list, which is discussed in section 4.1.9.

Python Programming – Updating List Elements Read More »

Python Programming – Data Structures – List Using Square Brackets

In this Page, We are Providing Python Programming – Data Structures – List Using Square Brackets. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Data Structures – List Using Square Brackets

List creation

The list can be created in many ways.

Using square brackets

As discussed before, the most common way of creating a list is by enclosing comma-separated values (items) between square brackets. Simply assigning a square bracket to a variable creates an empty list.

>>> a= [ ]
>>> a
[ ]
>>> type ( a ) 
< type ' list ’ >

Using other lists

A list can also be created by copying a list or slicing a list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> b=a [ : ]
>>> b
[ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> c=a [ 1 : 3 ]
>>> c
[ ' eggs ' , 100 ]

List comprehension

List comprehension provides a concise way to create a list. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses that follow it.

Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a sub-sequence of those elements that satisfy a certain condition. For example, creating a list of squares using an elaborate approach is as follows:

>>> squares= [ ]
>>> for x in range ( 10 ) :
. . . squares. append ( x**2 )
. . .
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 ]

The same can be obtained using list comprehension as:

squares= [ x**2 for x in range ( 10 ) ] 
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 ]

Alternatively, it can also be obtained using map ( ) built-in function:

squares=map ( 1ambda x : x**2 , range ( 10 ) )
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 ]

The following list comprehension combines the elements of two lists if they are not equal:

>>> [ ( x , y ) for x in [ 1 , 2 , 3 ] for y in [ 3 , 1 , 4 ] if x !=y ]
[ ( 1 , 3 ) , ( 1 , 4 ) , ( 2 , 3 ) , ( 2 , 1 ) , ( 2 , 4 ) , ( 3 , 1 ) , ( 3 , 4 ) ]

and it’s equivalent to:

>>> combs= [ ]
>>> for x in [ 1 , 2 , 3 ] :
. . . for y in [ 3 , 1 , 4 ] :
. . . if x !=y :
. . . combs. append ( ( x , y ) )
. . . 
>>> combs
[ ( 1 , 3 ) , ( 1 , 4 ) , ( 2 , 3 ) , ( 2 , 1 ) , ( 2 , 4 ) , ( 3 , 1 ) , ( 3 , 4 ) ]

Using built-in function

The list can also be created using a built-in function list ( ). The list ( [iterable] ) function returns a list whose items are the same and in the same order as iterable items. The iterable can be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned. If no argument is given, a new empty list is returned.

>>> list ( ( ' hi ' ' hello ' , ' bye ' ) )
[ ' hi ' , ' hello ' , ' bye ' ]
>>> list ( ' hello ' )
[ ' h ' , ' e ' , ' 1 ' , ' 1 ' , ' o ' ]
>>> list ( ( 10 , 50 , ) )
[ 10 , 50 ]
>>> list ( )
[ ]

Accessing list elements

Like string indices, list indices start at 0. To access values in a list, use the square brackets with the index or indices to obtain a slice of the list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 0 ] 
' spam ' 
>>> a [ 0 ] [ 1 ]
' p '
>>> a [ 1 : 3 ] 
[ ' eggs ' , 100 ]

Python Programming – Data Structures – List Using Square Brackets Read More »

Python Programming – List

In this Page, We are Providing Python Programming – List. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – List

List

Python has a number of built-in types to group together data items. The most versatile is the list, which is a group of comma-separated values (items) between square brackets. List items need not be of the same data type.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a
[ ' spam ' , ' eggs ' , 100 , 1234 ]

Python allows adding a trailing comma after the last item of list, tuple, and dictionary, There are several reasons to allow this:

  • When the list, tuple, or dictionary elements spread across multiple lines, one needs to remember to add a comma to the previous line. Accidentally omitting the comma can lead to errors that might be hard to diagnose. Always adding the comma avoids this source of error (the example is given below).
  • If the comma is placed in each line, it can be reordered without creating a syntax error.

The following example shows the consequence of missing a comma while creating a list.

>>> a=[
         ' hi ' , 
         ’ hello ’ 
         ' bye ’ , 
         ' tata ' , 
         ] 
>>> a
[ ' hi ' ,  ' hellobye ' ,  ' tata ' ]

This list looks like it has four elements, but it actually contains three: ‘ hi ‘,  ‘ hellobye ‘, and  ‘ tata ‘. Always adding the comma avoids this source of error.

Python Programming – List Read More »

Python Programming – List Methods

In this Page, We are Providing Python Programming – List Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – List Methods

List methods

Below are the methods of list-objects.

list . append ( x )
Add an item to the end of the list. It is same as list [ len ( list ) : len ( list ) ] = [ x ] .

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . append ( 45 )
>>> a
[ 66 . 25 , 333 , 333 , 1 , 1234 . 5 , 45 ] 
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a [ len ( a ) : len ( a ) ]=[ 45 ]
>>> a
[ 66 . 25 , 333 , 333 , 1 , 1234 . 5 , 45 ]

list . extend ( L )
Extend a list by appending all the items of a given list. It is same as list [ len ( list ) : len ( list ) ] =L.

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= [ 7 . 3 , 6 . 8 ]
>>> a . extend ( b )
>>> a
[ 66 . 25 , 333 , 333 , 1 , 1234 . 5 , 7 . 3 , 6 . 8 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= [ 7 . 3 , 6 . 8 ]
>>> a [ len ( a ) : len ( a ) ]=b 
>>> a
[ 66 . 25 , 333 , 333 , 1 , 1234 . 5 , 7 . 3 , 6 . 8 ]

list.insert ( i , x )
Insert an item at a given position in the list. The first argument i is the index before which an item x need to be inserted. It is same as list [i : i] = [x].

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . insert ( 2 , 5 . 7 )
>>> a
[ 66 . 25, 333 , 5 . 7 , 333 , 1 , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a [ 2 : 2 ] = [ 5 . 7 ]
>>> a
[ 66 . 25 , 333 , 5 . 7 , 333 , 1 , 1234 . 5 ]

list.index ( x [ , i [ , j ] ] )
Return the index in the list of the first occurrence of item x. In other words, it returns the smallest index k such that list [k]==x and i<=k<j. A ValueError exception is raised in absence of item x.

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . index ( 333 )
1

list.remove ( x )
Remove the first item from the list whose value is x. An error (ValueError exception) occur in absence of item x. It is same as del list [list. index (x) ].

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . remove ( 333 )
>>> a
[ 66 . 25 , 333 , 1 , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> del a [ a . index ( 333 ) ] 
>>> a
[ 66 . 25 , 333 , 1 , 1234 . 5 ]

list . pop ( [ i ] )
Remove the item at the given position i in the list, and return it. If no index is specified (defaults to -1), pop () removes and returns the last item in the list.

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . pop ( 3 )
1
>>> a
[ 66 . 25 , 333 , 333 , 1234 . 5 ]
>>> a . pop ( )
1234 . 5 
>>> a
[ 66 . 25 , 333 , 333 ]

list.count ( x )
Return the number of times item x appears in the list.

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . count ( 333 )
2

list.reverse ( )
Reverse the element’s position in the list; no new list is returned. It is same as list=list [: : -1 ].

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . reverse ( )
>>> a 
[ 1234 . 5 , 1 , 333 , 333 , 66 . 25 ] 
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a=a [ : : -1 ] 
[ 1234 . 5 , 1 , 333 , 333 , 66 . 25 ]

list.sort ( [ cmp [ , key [ , reverse ] ] ] )
Sort the items of the list; no new list is returned. The optional arguments have same meaning as given in sorted () built-in function.

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> a . sort ( ) 
>>> a
[ 1 , 66 . 25 , 333 , 333 , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ' ab ' , 1234 . 5 ] 
>>> a . sort ( )
>>> a
[ 1 , 66 . 25 , 333 , 333 , 1234 . 5 , ' ab ' , ' abc ' ]
>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ' ab ' , 1234 . 5 ]
>>> a . sort ( reverse=True )
>>> a
[ ' abc ' , ' ab ' , 1234 . 5 , 333 , 333 , 66 . 25 , 1 ]

Using list as Stack

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out” approach). To add an item to the top of the stack, use append (). To retrieve an item from the top of the stack, use pop ( ) without an explicit index. For example:

>>> stack= [ 3 , 4 , 5 ]
>>> stack . append ( 6 )
>>> stack . append ( 7 )
>>> stack
[ 3 , 4 , 5 , 6 , 7 ]
>>> stack . pop ( )
7
>>> stack [ 3 , 4 , 5 , 6 ]
>>> stack . pop ( )
6
>>> stack . pop ( )
5
>>> stack 
[ 3 , 4 ]

Using list as queue

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, list is not efficient for this purpose. While appending and popping of elements from the end of list are fast, doing inserting and popping from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections. deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque
>>> queue=deque ( [ " Eric " , " John " , " Michael " ] )
>>> queue . append ( " Terry " )
>>> queue . append ( " Graham " )
>>> queue 
deque ( [ ' Eric ' , ' John ' , ' Michael ' , ' Terry ' , ' Graham ' ] ) 
>>> queue . popleft ( )
' Eric '
>>> queue . popleft ( ) 
' John '
>>> queue
deque ( [ ' Michael ' , ' Terry ' , ' Graham ' ] )

Python Programming – List Methods Read More »

Python Programming – Compound statement

In this Page, We are Providing Python Programming – Compound statement. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement

Compound statement

Compound statements contain groups of other statements, they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although a whole compound statement can be contained in one line.

The if, while, and for statements are the traditional control flow compound statements, try to specify exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.

Compound statements consist of one or more clauses. A clause consists of a header and a suite. The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of the suite can contain nested compound statements.

The colon is required primarily to enhance readability.

if a == b
print aversus

if a == b:
print a

Notice how the second one is slightly easier to read. Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased.

A code block (or simply “block”) is a piece of Python program text that is executed as a unit. Few examples of blocks are a module, a function body, a class definition, etc. Each command typed interactively is a block.

If statement

The if statement is used for conditional execution:

if_stmt : : = " if " expression " : " suite
( " elif " expression " : " suite ) *
["else" " : " suite]

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true, then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause (if present) is executed.

>>> var=100 
>>> if var==100 :
. . .             print ' var has value 100 '
. . .
var has a value of 100 
>>>
>>> var=100 
>>> if var<> 100 :
. . .           print ' var does not have value 100 '
. . . else:
. . .           print 'var has value 100'
. . .
var has a value of 100 
>>>
>>> var=100 
>>> if var<100 : 
. . .            print ' var has value less than 100 '
. . . elif var>100 : 
. . .            print ' var has value greater than 100'
. . . else:
. . .           print ’ var has value 100 '
. . .
var has a value of 100

The following example shows that if the evaluation of expression gives a result either None, an empty string (‘ ‘), zero (0), or Boolean False, then the condition is considered as false.

>>> if None or ' ' or 0 or False:
. . .          print ' Atleast one condition is true ' 
. . . else:
. . .           print 'None of the condition is true'
. . . 
None of the condition is true

There may be a situation when there is a need to check for another condition after a condition resolves to true. In such a situation, the nested if statement can be used.

>>> var=100
>>> if isinstance ( var , str) :
. . .                 print ' var is a string '
. . . elif (type(var) is int) :
. . .          if var<> 100 :
. . .             print ' var does not have value 100 '
. . . else:
. . .        print 'var has value 100'
. . .
var has a value of 100

While statement

The while statement is used for repeated execution of a group of statements as long as an expression is true:

while_stmt " while " expression " : "  suite
[ " else " suite ]

This compound statement repeatedly tests the expression, and if it is true, it executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause (if present) is executed and the loop terminates.

>>> var=1
>>> while var<=5: 
. . .  print ' Count ',var
. . .  var=var+l
. . .
Count 1
Count 2 
Count 3
Count 4 
Count 5
>>> print ' The loop ends '
The loop ends

The above code can also be witten as follows:

>>> var=l
>>> while var<=5 :
. . .         print ' Count ' , var
. . .   var=var+1
. . . else:
. . .     print 'The loop ends'
. . .
Count 1 
Count 2 
Count 3 
Count 4 
Count 5 
The loop ends

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

>>> var=l
>>> while var<=5:
. . .   print  ' Count ', var
. . .     var=var+1
. . .      if var==4:
. . .        break
. . . else:
. . .        print ' The loop ends '
. . .
Count 1 
Count 2 
Count 3

A continuous statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

>>> var=0
>>> while var<=5:
. . .         var=var+1
. . .         if var>=3 and var<=4:
. . .              continue
. . .     print 'Count ',var
. . .
Count 1 
Count 2 
Count 5
Count 6

Consider a scenario where the condition never becomes false. This results in a loop that never ends; such a loop is called an infinite loop. One needs to use the keyboard Ctrl+C to come out of the program.

For statement

The for statement is used to iterate over the elements of a sequence (such as a string, tuple, or list) or another iterable object:

for_stmt :  : = " for " target_list " in " expression_list " : " suite 
                            [ " else " suite ]

The expression list expression_list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item, in turn, is assigned to the target list target_list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause (if present) is executed, and the loop terminates.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . print ' Count ' , i
. . .
Count 1 
Count 2 
Count 3 
Count 4 
Count 5
>>> print ' The loop ends '
The loop ends

The above code can also be written as follows:

>>> for i in range ( 1 , 6 ) :
. . .         print ' Count ' , i
. . . else : 
. . .           print 'The loop ends'
. . .
Count 1 
Count 2 
Count 3
Count 4 
Count 5
The loop ends

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . if i==4 :
. . .  break
. . .    print ' Count ' , i
. . . else :
. . .      print  ' The loop ends '
. . .
Count 1 
Count 2 
Count 3

A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . if i==4 :
. . . continue
. . .         print  ' Count  ' , i
. . .  else :
. . .       print  ' The loop ends '
. . . 
Count 1 
Count 2 
Count 3 
Count 5 
The loop ends

There might be a scenario where one needs to print the item along with its index. The following example demonstrates this scenario using enumerate () built-in function (discussed later in this chapter).

>>> shuttles= [ ' Columbia ' , ' endeavour ' , ' challenger ' ]
>>> for index , value in enumerate ( shuttles ) :
. . . print index, value
. . .
0 Columbia
1 endeavor
2 challenger 
>>>
>>> value
'challenger'
>>> index 
2

It can also be observed that the target list is not deleted when the loop is finished.

Python Programming – Compound statement Read More »

Python Programming – Simple statement

In this Page, We are Providing Python Programming – Simple statement. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Simple statement

Simple statement

A simple statement is comprised within a single logical line. Several simple statements may occur on a single physical line separated by semicolons. The extended BNF notation describing syntax for simple statement is:

simple__stmt : := expression_stmt
                            | assert_stmt 
                            | assignment_stmt 
                            | augmented_assignment_stmt 
                            | pass_stmt 
                            | del_stmt
                            | print_stmt 
                            | return_stmt
                            | yield_stmt 
                            | raise_stmt
                            | break_stmt 
                            | continue_stmt
                            | import_stmt 
                            | global_stmt 
                            | exec_stmt

This book will discuss some of the simple statements.

Expression statement

An expression in a programming language is a combination of values, constants, variables, operators, functions etc. that are interpreted according to the particular rules of precedence for a particular programming language, which computes and then returns another value. This process is called evaluation. An expression statement evaluates the expression list (which may be a single expression).

expression_stmt : := expression_list

The following are examples of expression statements and their evaluation.

>>> 4 
4
>>> 4==4 
True 
>>> 2+6 
8
>>> ' Hi ' * 3 
' HiHiHi '

Assignment statement

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects. The following example shows binding value 4 to object (or name) a.

>>> a=4

Pass statement

The pass statement is a null operation, nothing happens when it is executed. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

pass_stmt  : : =  " pass "

The following example defines a function f and does nothing.

>>> def f ( arg ) :
. . .      pass
. . .

Del statement

This statement deletes each target in target_list from left to right.

del_stmt : := " del " target_list

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

>>> a = [ -1 , 1 , 66  .25 , 333 , 333 , 1234 . 5 ]
>>> del a [ 0 ]
>>> a
[ 1 , 66 . 25 , 333 ;  333 , 1234 . 5 ]
>>> del a [ 2 : 4 ]
>>> a
[ 1 , 66 . 25 , 1234 . 5 ]
>>> del a [ : ]
>>> a
[ ]
>>> a = [ -1 , 1 , 66 . 25 , 333 , 333 , 1234 . 5 ]
>>> del a
>>> a

Traceback ( most recent call last ) :
    File " <pyshell#24> " , line 1 , in <module> 
         a
NameError: name ' a ' is not defined

Print statement

The print statement evaluates each expression and then writes the resulting object to standard output (computer screen). If an object is not a string, it is first converted to a string using the rules for string conversion, the resulting or original string is then written. Space is written before each object is (converted and) written unless the output system believes it is positioned at the beginning of a line. A ‘ \n’ character is written at the end unless the print statement ends with a comma. If only the print keyword is there in the print statement, then only the ‘ \ n ‘ character is written. Following is a script “print_example.py”, having the following code:

a=20 
print ' hi ' , 5 , a 
print ' bye ' , 10 , a 
print 
print ' hi ' , 5 , a ,
print ' bye ' , 10 , a ,

Output after running the script is:

>>> runfile ( ' C : / Temp / print_example . py ' , wdir=r ' C : / Temp ' ) 
hi 5 20 
bye 10 20

hi 5 20 bye 10 20

Return statement

The return statement leaves the current function call with the expression_list (or None) as the return value.

return_stmt : := " return " [ expression_list ]

The following script ” addition_example . py ” demonstrate the use of return statement.

def summation ( arg1 , arg2 ) :
       return arg1+arg2

print ' Sum is : ' , summation ( 1 , 2 )

def summation ( arg1 , arg2 ) :        # The function return None
       print ' Sum is: ' , arg1+arg2

summation ( 3 , 4 ) 
print summation ( 3 , 4 )

def summation ( arg1 , arg2 ) :        # The function return None
print 'Sum is: ',arg1+arg2
return

summation ( 5 , 6 ) 
print summation ( 5 ,6)

def summation(argl,arg2):               # The function return None
    print ' Sum is: ' , arg1+arg2
    return None

summation ( 7 , 8 ) 
print summation ( 7 , 8 )

def summation ( arg1 , arg2) : 
def add ( arg1 , arg2) : 
        return arg1+arg2 
return add (arg1 , arg2 )

print ' Sum is : ' , summation ( 9 , 10)

The output after running the script is:

>>> runfile ( ' C : / Temp / addition_example . py ' , . wdir=r ' C : / Temp ' )
Sum is: 3
Sum is: 7 
Sum is: 7
None
Sum is: 11
Sum is: 11
None
Sura is: 15
Sum is: 15
None
Sum is: 19

Break statement

The break statement terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

break_stmt : : = " break "

If a for loop is terminated by break, the loop control target keeps its current value. The following script ” break_example . py ” demonstrates the use of the break statement.

a=5
for i in range ( 10 ) : 
    if i==a: 
          break 
  else:
        print i

print i

The output after running the script is:

>>> runfile ( ' C : / Temp / addition_example . py ' , wdir= r ' C : / Temp ' )
0 
1
2
3
3 
5

Continue statement

The continue statement makes the current nearest enclosing loop skip one iteration and executes the remaining ones.

continue_stmt : : = " continue "

The following script ” continue_example . py ” demonstrate the use of the continue statement.

for i in range ( 10 ) : 
     if i>4 and i<8 : 
     continue 
else: 
     print i

The output after running the script is:

>>> runfile ( ' C : / Temp / continue_example . py ' , wdir= r ' C : / Temp ' )
0
1
2
3
4
8
9

Import statement

Definitions (variables, function definitions, etc.) from one module can be imported into another module using an import statement. For more information, please refer to chapter 5.

Global statement

The global statement is a declaration that makes listed identifiers to be interpreted as global. This will become clearer by referring to section 3.2.5.

global_stmt : := " global " identifier ( " , " identifier) *

Python Programming – Simple statement Read More »