Author name: Prasanna

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 »

Python Programming – Compound statement Parameter

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

Python Programming – Compound statement Parameter

Parameter

The parameter is a named entity in a function (or method) definition that specifies the argument (or in some cases, arguments), that the function can accept. Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. For example, given the function definition:

def func ( foo , bar=None , ** kwargs ) : 
              pass

foo, bar, and kwargs are parameters of f unc. However, when calling f unc, for example:

f unc ( 42 , bar=314 , extra=somevar )

the values 42 , 314 , and somevar are arguments.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).

>>> def changeme ( mylist ) :
. . .               mylist.append ( [ 1 , 2 , 3 , 4 ] )
. . .               print "Values inside the function:  " , mylist
. . .               return
. . . 
>>> mylist= [ 10 , 20 , 30 ] 
>>> changeme ( mylist )
Values inside the function: [ 10 , 20 , 30 , [ 1 , 2 , 3 , 4 ] ]
>>> print "Values outside the function:  " , mylist 
Values outside the function: [ 10 , 20 , 30 , [ 1 , 2 , 3 , 4 ] ]

In the above example, the append operation maintains the passed object reference. In the following example, the object reference is overwritten inside the function.

>>> def changeme ( mylist ) :
. . .          mylist= [ 1 , 2 , 3 , 4 ]
. . .          print "Values inside the function: ",mylist
. . .         return
. . . 
>>> mylist= [ 10 , 20 , 30 ]
>>> changeme ( mylist )
Values inside the function: [ 1 , 2 , 3 , 4 ]
>>> print "Values outside the function:  " , mylist 
Values outside the function: [ 10 , 20 , 30 ]

There are four types of parameters:

Positional or keyword parameter

It specifies that an argument can be passed either positionally or as a keyword argument. Note that, only those parameters which are at the end of the parameter list can be given default argument values i.e. the function cannot have a parameter with a default argument value preceding a parameter without a default argument value in the function’s parameter list. This is because the values are assigned to the parameters by position. For example, def func ( a , b=5 ) is valid, but def func ( a=5 , b ) is not valid.

Only positional parameter

It specifies that an argument can be supplied only by position.

Var-positional parameter

It specifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with *.

Var-keyword parameter

It specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prefixing the parameter name with **.

Following are few examples of functions.

>>> def person_info ( fn , In , ag , tel=5128975 , nat=' American ' ) :
. . .               print ' First name : ' , fn
. . .               print ' Last name : ' , In
. . .               print ' Age : ' , ag 
. . .               print ' Telephone number : ' , tel
. . .               print ' Nationality : ' , nat
. . . 
>>> person_info ( ’ Sachin ' , ' Tendulkar ' , 40 , 17896823 , ' Indian ' ) 
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 17896823 
Nationality: Indian
>>> person_info ( ' Mike ' , ' Johnson ' , 20 )
First name: Mike 
Last name: Johnson 
Age: 20
Telephone number: 5128975 
Nationality: American
>>> person_info ( ' Nadeem ' , ' Khan * , 54 , nat= ' Pakistani ' )
First name: Nadeem 
Last name: Khan 
Age: 54
Telephone number: 5128975 
Nationality: Pakistani
>>> person_info ( ' Chin ' , ' Chan ' , 15 , nat= ' Chinese ’ , tel=1894313654 ) 
First name: Chin 
Last name: Chan 
Age: 15
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def person_info ( fn , In , ag , tel , nat ) :
. . .                   print ' First name: ' , fn
. . .                   print ' Last name: ' , In
. . .                   print ' Age: ' , ag
. . .                   print ' Telephone number: ' , tel
. . .                   print ' Nationality: ' , nat
. . . 
>>> person_info ( ' Sachin ' , ' Tendulkar ' , 40,17896823, ' Indian') 
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 17896823 
Nationality: Indian
>>> person_info ( ' Chin ' , ' Chan ' , 15 , 1894313654 , ' Chinese ' ) 
First name: Chin 
Last name: Chan 
Age: 15
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def total ( a , b , *numbers ) :
. . .      tot=a+b
. . .      for num in numbers:
. . .      tot=tot+num
. . .      return tot
. . .
>>> print ' Total : ' , total ( 1 , 2 , 3 , 4 , 5 )
Total : 15
>>> print ' Total : ' , total ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
Total : 55 
>>>
>>> def person_info ( fn= ' Chinln = ' Chan ' , ** more_info ) :
. . .         print ' First name : ' , fn
. . .         print ' Last name : ' , In
. . .         if more_info.has_key ( ' ag ' ) :
. . .               print ' Age : ' , more_info [ ' ag ' ]
. . .         if more_info.has_key ( ' tel ' ) :
. . .              print ' Telephone number : ' , more_info [ ' tel ' ]
. . .         if more_info.has_key ( ' nat ' ) :
. . .              print ' Nationality : ' , more_info [ ' nat ' ] 
. . . 
>>> person_info ( )
First name: Chin 
Last name: Chan
>>> person_info ( ag=40 , tel=1789 , ln= ' Tendulkar ' , nat= ' Indian ' , fn= ' sachin ' )
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 1789 
Nationality: Indian
>>> personl_info ( ag=15 , nat= ' Chinese ' , tel=l894313654 )
First name: Chin
Last name: Chan
Age: 15 
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def total( a , b , *numbers , **kwag ) :
. . .       tot=a+b 
. . .       for num in numbers:
. . .            tot=tot+num
. . .      for key in kwag:
. . .           tot=tot+kwag [ key ]
. . .      return tot
. . . 
>>> print ' Total : ' , total ( 5 , 7 , 10 , 2 , 14 , c=100 , d=106 , e=211 ) 
Total: 455

Python Programming – Compound statement Parameter Read More »

Python Programming – Compound statement Functions

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

Python Programming – Compound statement Functions

Functions

The function is a compound statement which returns some value to the caller. The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.

The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or “docstring”. Docstring is a string literal that appears as the first expression in a class, function, or module. While ignored when the suite is executed, it is recognized by the compiler and put into the doc attribute of the enclosing class, function, or module.

>>> def summation ( a , b ) : 
. . . " " " Gives sum of
. . .            two numbers " " "
. . .      sum=a+b
. . .     return sum
>>> summation ( 5 , 10 )
15
>>> summation. ________ doc_______
' Gives sum of \ n            two numbers '

Python Programming – Compound statement Functions Read More »

Python Programming – Compound statement Functions Argument

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

Python Programming – Compound statement Functions Argument

Argument

The argument is the value passed to a function (or method) while calling the function. There are two types of arguments:

Keyword argument

Keyword argument is an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 10, 20, 30, and 40 are keyword arguments in the following calls to summation ( ) function:

>>> def summation( aa , bb , cc , dd ) : 
. . .                    print ' aa : ' , aa
. . .                    print ' bb : ' , bb
. . .                    print ' cc : ' , cc
. . .                    print ' dd : ' , dd
. . .                    total=aa+bb+cc+dd
. . .                    return total
. . .
>>> sumupl=summation( bb=20 , dd=40 , aa=10 , cc=30 )
aa : 10
bb : 20
cc : 30
dd : 40 
>>> print ' Sum is: ' , sumupl 
Sum is : 100
>>> sumup2=summation(** { ' bb ' : 20 , ' dd ' : 40 , ' aa ' : 10 , ' cc ' : 30 } ) 
aa : 10
bb : 20 
cc : 30
dd : 4 0
>>> print 'Sum is:',sumup2 
Sum is: 100

Positional argument

Positional argument is an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and can also be passed as elements of an iterable preceded by *. For example, 10, 20, 30 and 40 are positional arguments in the following calls to summation ( ) function:

>>> def summation ( aa , bb , cc , dd ): 
. . .           print ' aa : ' , aa
. . .           print ' bb : ' , bb
. . .           print ' cc : ' , cc
. . .           print ' dd  : ', dd
. . .           total=aa+bb+cc+dd
. . .           return total
>>> sumup3=summation( 10 , 20 , 30 , 40 )
aa : 10
bb : 20
cc : 30
dd : 40
>>> print 'Sum is:',sumup3 
Sum is : 100
>>> sumup4=summation( * ( 10 , 20 , 30 , 40 ) )
aa : 10
bb : 20
cc : 30
dd : 40
>>> print ' Sum is :  ',sumup4 
Sum is : 100

Python Programming – Compound statement Functions Argument Read More »

Python Programming – Scope

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

Python Programming – Scope

Scope

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one. The scope of names defined in a class block is limited to the class block. If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. The variables of the module code block are local and global.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and the programmer need to explicitly declare it as global.

The scope is bit difficult to understand, the following examples might prove fruitful.

def f ( ) :
        print s
s=" I hate spam "
f ( )

The variable s is defined as the string “I hate spam”, before the function call f ( ). The only statement in f ( ) is the print statement. As there is no local variable s in f ( ), the value from the global s will be used. So the output will be the string “I hate spam”. The question is, what will happen, if the programmer changes the value of s inside of the function f ( ) ? Will it affect the global s as well? The test is in the following piece of code:

def f ( ) :
      s="Me too." 
      print s
s=" I hate spam." 
f ( )
print s

The output looks like the following. It can be observed that s in f ( ) is local variable of f ( ).

Me too.
I hate spam.

The following example tries to combine the previous two examples i.e. first access s and then assigning a value tp it in function
f ( ).

def f ( ) :
    print s 
    s="Me too." 
    print s

s=" I hate spam." 
f ( )
print s

The code will raise an exception- UnboundLocalError: local variable ‘s’ referenced before assignment

Python assumes that a local variable is required due to the assignment to s anywhere inside f ( ), so the first print statement gives the error message. Any variable which is changed or created inside of a function is local, if it has not been declared as a global variable. To tell Python to recognize the variable as global, use the keyword global, as shown in the following example.

def f ( ) :
      global s 
      print s
      s=" That's clear." 
      print s

s="Python is great ! " 
f ( )
print s

Now there is no ambiguity. The output is as follows:

Python is great !
That's clear.
That's clear.

Local variables of functions cannot be accessed from outside the function code block.

def f ( ) :
s=" I am globally not known" 
       print s
f ( )
print s

Executing the above code will give following error message- NameError : name ‘s’ is not defined

Python Programming – Scope Read More »

Python Programming – Exceptions

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

Python Programming – Exceptions

Exceptions

The exception is a way of breaking out of the normal flow of control of a code block in order to handle the error or other exceptional conditions. An exception is raised at the point where the error is detected.

>>> while True print ' Hello world '
SyntaxError: invalid syntax 
>>> 10 / 0

Traceback (most recent call last) : 
File "<pyshell#l>", line 1, in <module>
    10 / 0 
ZeroDivisionError: integer division or modulo by zero 
>>> 4+tt*3

Traceback (most recent call last) :
File "<pyshe11#2>", line 1, in <module>
4+tt*3
NameError: name ' tt ' is not defined 
>>> ' 5 '+7

Traceback (most recent call last) :
File "<pyshe11#3>", line 1, in <module>
' 5 '+7
TypeError: cannot concatenate ' str ' and ' int ' objects

The last line of the error message indicates what went wrong. Exceptions are of different types, and the type is printed as part of the message; the types in the above example are SyntaxError, ZeroDivisionError, NameError, and TypeError. Standard exception names are built-in identifiers (not reserved keywords). The rest of the lines provides detail based on the type of exception and what caused it.

Handling exceptions

If there is some suspicious code that may raise an exception, it can be handled by placing the suspicious code in a try compound statement. After the try clause, include an except clause, followed by a block of code that handles the problem. The following example attempts to open a file and write something in the file.

# ! / usr / bin / python 
try :
     fh = open ( " testflie " , " w " )
     fh.write ( " This is my test file for exception handling ! ! " ) 
except IOError :
print " Error: can\'t find the file or read data " 
else: 
print " Written content in the file successfully " 
fh.close ( )

Here are few important points that need to be remembered:

  • A single try statement can have multiple except clauses. This is useful when the try clause contains statements that may throw different types of exceptions.
  • A generic except clause can be provided, which handles any exception.
  • After the except clause(s), and else clause can be included. The code in the else clause is executed, if the code in the try clause does not raise an exception.

Python Programming – Exceptions Read More »