Author name: Prasanna

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 »

Python Programming – Basics of Python

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

Python Programming – Basics of Python

Token

A token is a string of one or more characters that is significant as a group. Consider an expression:

sum=6+2

The tokens in the above expression are given in table 2-1:

Token

Token type

Sum

Identifier

=

Assignment operator

6

Integer literal

+

Addition operator

2

Integer literal

The process of converting a sequence of characters into a sequence of tokens is called “lexical analysis”. A program or function that performs lexical analysis is called a lexical analyzer, lexer, or tokenizer. A lexer is generally combined with a parser (beyond the scope of this book), which together analyze the syntax of computer language. Python supports the following categories of tokens: NEWLINE, INDENT, DEDENT, identifiers, keywords, literals, operators, and delimiters.

Keywords

The following identifiers (as shown as output in the following code) are used as reserved words (or “keywords”) of the language, and cannot be used as ordinary identifiers.

>>> import keyword
>>> for kwd in keyword.kwlist:
. . .    print kwd
. . .
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield

One can also check if an identifier is a keyword or not using its keyword ( ) function.

>>> import keyword
>>> keyword . iskeyword ( ' hi ' )
False
>>> keyword . iskeyword ( ' print ' )
True

Delimiters

The delimiter is a character that separates and organizes items of data. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values. Table 2-11 provides a list of tokens that serves as delimiters in Python.

Delimiters

()[]@{},:.;=
+=-=*=/=//=%=&=l=∧=>>=<<=**=

The following example shows how the use of delimiters can affect the result.

 

>>> 5+6/2                                         # no delimiter used
8 . 0
>>> (5+6)/2                                      # delimiter used
5 . 5

Following are few points that a Python programmer should be aware of:

  • The period (.) can also occur in floating-point and imaginary literals.
  • The simple and augmented assignment operators, serve lexically as delimiters but also perform operations.
  • ASCII characters “, #, and \ have special meaning as part of other tokens or are otherwise significant to the lexical analyzer.
  • Whitespace is not a token but serves to delimit tokens.

Integer function

The following function operates on integers (plain and long).

int.bit_length ( )
Return the number of bits necessary to represent an integer (plain or long) in binary, excluding the sign and leading zeros.

>>> n=-37
>>> bin(n)       # bin ( ) convert' integer number to a binary string
' -0b100101 ' 
>>> n.bit_length ( )
6 
>>> n=2**31 
>>> n
2147483648L 
>>> bin(n)
'0b10000000000000000000000000000000'
>>> n.bit_length ( )
32

Float functions

Some of the functions for floating-point numbers are discussed below.

float.as_integer_ratio ( )
Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator.

>>> ( -0 .25 ) . as_integer_ratio ( )
(-1 , 4)

float.is_integer ( )
Return True if the float instance is finite with integral value, otherwise it return False.

>>> (-2 . 0) . is_integer ( )
True
>>> (3 . 2) . is_integer ( )
False

Python Programming – Basics of Python Read More »

Basics of Python – Error

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

Basics of Python – Error

Error

An error (or software bug) is a fault in a computer program that produces an incorrect or unexpected result or causes it to behave in unintended ways. Most bugs arise from mistakes and errors made by people in either a program’s source code or its design. Usually, errors are classified as: syntax error, run-time error, and logical error.

Syntax error

Syntax error refers to an error in the syntax of tokens and/or sequence of tokens that are intended to be written in a particular programming language. For compiled languages, syntax errors occur strictly at compile-time. A program will not compile until all syntax errors are corrected. For interpreted languages, however, not all syntax errors can be reliably detected until run-time.

>>> prin ' Hi '
SyntaxError: invalid syntax 
>>> print " Hi '
SyntaxError: EOL while scanning string literal

Run-time error

A run-time error is an error that can be detected during the execution of a program. The code appears to be correct (it has no syntax errors), but it will not execute. For example, if a programmer has written a correct code to open a file using the open ( ) function, and if the file is corrupted, the application cannot carry out the execution of the open ( ) function, and it stops running.

Logical error

A logical error (or semantic error) is a bug in a program that causes it to operate incorrectly, but not terminate abnormally. A logical error produces an unintended or undesired output or other behavior, although it may not immediately be recognized. The logic error occurs both in compiled and interpreted languages.

Unlike a program with a syntax error, a program with a logical error is a valid program in the language, though it does not behave as intended. The only clue to the existence of logic errors in the production of wrong solutions. For example, if a program calculates the average of variables a and b, instead of writing the expression c= (a+b) / 2, one can write c=a+b / 2, which is a logical error.

>>> print a+b / 2 
6 . 5
>>> print ( a+b ) / 2
5 . 0

Basics of Python – Error Read More »

Basics of Python – Built-in Types

In this Page, We are Providing Basics of Python – Built-in Types. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Built-in Types

Built-in types

This section describes the standard data types that are built into the interpreter. There are various built-in data types, for e.g., numeric, sequence, mapping, etc., but this book will cover few types. Schematic representation of various built-in types is shown in figure 2-1.

Python Handwritten Notes Chapter 2 img 1

Numeric types

There are three distinct numeric types: integer, floating-point number, and complex number.

Integer

Integer can be sub-classified into three types:

Plain integer

Plain integer (or simply ” integer “) represents an integer number in the range -2147483648 through 2147483647. When the result of an operation would fall outside this range, the result is normally returned as a long integer.

>>> a=2147483647 
>>> type (a) 
<type ' int '>
>>> a=a+1
>>> type (a)
<type ' long '>
>>> a=-2147483648 
>>> type (a)
<type ' int '>
>>> a=a-1
>>> type (a)
<type ' long ’>

The built-in function int(x = 0) converts a number or string x to an integer or returns 0 if no arguments are given.

>>> a =' 57 '
>>> type (a) 
<type ' str '>
>>> a = int (a)
>>> a 
57
>>> type (a)
<type ' int '>
>>> a = 5.7
>>> type (a)
<type ' float '> 
>>> a = int (a)
>>> a 
5 
>>> type (a)
<type ' int '>
>>> int( )
0

Long integer

This represents integer numbers in a virtually unlimited range, subject to available memory. The built-in function long (x=0) converts a string or number to a long integer. If the argument is a string, it must contain a possibly signed number. If no argument is given, OL is returned.

>>> a = 5 
>>> type (a) 
<type ' int '> 
>>> a = long (a) 
>>> a 
5L
>>> type (a) 
<type ' long '> 
>>> long ( )
OL
>>> long (5)
5L
>>> long (5.8) 
5L
>>> long(' 5 ') 
5L
>>> long(' -5 ')
-5L

Integer literals with an L or 1 suffix yield long integers (L is preferred because 11 looks too much like eleven).

>>> a=10L 
>>> type (a) 
<type ' long '>
>>> a=101 
>>> type (a)
<type ' long '>

The following expressions are interesting.

>>> import sys 
>>> a=sys.maxint 
>>> a
2147483647
>>> type (a)
<type ' int '>
>>> a=a+1
>>> a
21474836 48L
>>> type (a)
<type ' long ’>

Boolean

This represents the truth values False and True. The boolean type is a sub-type of plain integer, and boolean values behave like the values 0 and 1. The built-in function bool ( ) converts a value to boolean, using the standard truth testing procedure.

>>> bool ( ) 
False 
>>> a=5
>>> bool (a)
True
>>> bool (0)
False
>>> bool( ' hi ' )
True
>>> bool(None)
False
>>> bool(' ')
False
>>> bool(False)
False
>>> bool("False" )
True
>>> bool(5 > 3)
True

Floating point number

This represents a decimal point number. Python supports only double-precision floating-point numbers (occupies 8 bytes of memory) and does not support single-precision floating-point numbers (occupies 4 bytes of memory). The built-in function float  ( ) converts a string or a number to a floating-point number.

>>> a = 57 
>>> type (a)
<type ' int '>
>>> a = float (a)
>>> a
57.0 
>>> type (a)
<type ' float '>
>>> a = ' 65 ' 
>>> type (a)
<type ' str ' > 
>>> a = float (a) 
>>> a
65.0 
>>> type (a)
<type ' float '>
>>> a = 1e308 
>>> a 
1e+30 8 
>>> type (a)
<type ' float '>
>>> a = 1e309 
>>> a
inf 
>>> type (a)
<type ' float '>

Complex number

This represents complex numbers having real and imaginary parts. The built-in function complex () is used to convert numbers or strings to complex numbers.

>>> a = 5.3
>>> a = complex (a)
>>> a 
(5 . 3 + 0 j)
>>> type (a)
<type ' complex '>
>>> a = complex ( )
>>> a
0 j 
>>> type (a)
<type ' complex '>

Appending j or J to numeric literal yields a complex number.

>>> a = 3 . 4 j 
>>> a 
3 . 4 j
>>> type (a)
<type ' complex '>
>>> a = 3 . 5 + 4 . 9 j 
>>> type (a)
<type ' complex '>
>>> a = 3 . 5+4 . 9 J
>>> type (a)
<type ' complex '>

The real and imaginary parts of a complex number z can be retrieved through the attributes z. real and z. imag.

a=3 . 5 + 4 . 9 J
>>> a . real
3 . 5
>>> a . imag 
4 . 9

Sequence Types

These represent finite ordered sets, usually indexed by non-negative numbers. When the length of a sequence is n, the index set contains the numbers 0, 1, . . ., n-1. Item i of sequence a is selected by a [i]. There are seven sequence types: string, Unicode string, list, tuple, bytearray, buffer, and xrange objects.

The sequence can be mutable or immutable. The immutable sequence is a sequence that cannot be changed after it is created. If an immutable sequence object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change. The mutable sequence is a sequence that can be changed after it is created. There are two intrinsic mutable sequence types: list and byte array.

Iterable is an object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like diet and file, etc. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map (), …). When an iterable object is passed as an argument to the built-in function iter (), it returns an iterator for the object. An iterator is an object representing a stream of data; repeated calls to the iterator’s next () method return successive items in the stream. When no more data are available, a Stoplteration exception is raised instead.

Some of the sequence types are discussed below:

String

It is a sequence type such that its value can be characters, symbols, or numbers. Please note that string is immutable.

>>> a=' Python : 2 . 7 '
>>> type (a)
<type ' str ’>
>>> a [2 ] =' S '
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

The built-in function str (object =’ ‘ ) returns a string containing a nicely printable representation of an object. For strings, this returns the string itself. If no argument is given, an empty string is returned.

>>> a=57.3
>>> type(a) 
<type 'float'>
>>> a=str(a)
>>> a
' 57.3 '
>>> type (a)
<type ' str '>

Tuple

A tuple is a comma-separated sequence of arbitrary Python objects enclosed in parenthesis (round brackets). Please note that the tuple is immutable. A tuple is discussed in detail in chapter 4.

>>> a=(1 , 2 , 3 ,4) 
>>> type (a)
<type ' tuple '>
'a', 'b', 'c')

List

The list is a comma-separated sequence of arbitrary Python objects enclosed in square brackets. Please note that list is mutable. More information on the list is provided in chapter 4.

>>> a=[1, 2 ,3, 4]
>>> type(a) 
<type ' list '>

Set types

These represent an unordered, finite set of unique objects. As such, it cannot be indexed by any subscript, however, they can be iterated over. Common uses of sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. There are two set types:

Set

This represents a mutable set. It is created by the built-in function set (), and can be modified afterward by several methods, such as add () remove (), etc. More information on the set is given in chapter 4.

>>> set1=set ( )                                                    # A new empty set
>>> set1.add (" cat ")                                           # Add a single member
>>> set1.update ([" dog "," mouse "])                 # Add several members
>>> set1.remove ("mouse")                                # Remove member
>>> set1
set([' dog ', ' cat '])
>>> set2=set([" dog "," mouse "])
>>> print set1&set2                                           # Intersection
set ( [' dog ' ] )
>>> print set1 | set2                                           # Union
set([' mouse ', ' dog ', ' cat '])

The set ( [ iterable ] ) return a new set object, optionally with elements taken from iterable.

Frozenset

This represents an immutable set. It is created by a built-in function frozenset ( ). As a frozenset is immutable, it can be used again as an element of another set, or as a dictionary key.

>>> frozenset ( ) 
frozenset ( [ ] )
>>> frozenset (' aeiou ') 
frozenset{ [' a ', ' i ',' e ',' u ',' o '])
>>> frozenset ( [0, 0, 0, 44, 0, 44, 18] ) 
frozenset (10, 18, 44])

The frozenset ( [iterable] ) return return a new frozenset object, optionally with elements taken from iterable.

Mapping Types

This represents a container object that supports arbitrary key lookups. The notation a [k] selects the value indexed by key k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len () returns the number of items in a mapping. Currently, there is a single mapping type:

Dictionary

A dictionary is a mutable collection of unordered values accessed by key rather than by index. In the dictionary, arbitrary keys are mapped to values. More information is provided in chapter 4.

>>> dict1={"john":34,"mike":56}
>>> dict1[" michael "] = 42 
>>> dict1
{' mike ' : 56, ' john ' : 34, ' michael ' : 42}
>>> dictl[" mike "]
56

None

This signifies the absence of a value in a situation, e.g., it is returned from a function that does not explicitly return anything. Its truth value is False.

Some other built-in types such as function, method, class, class instance, file, module, etc. are discussed in later chapters.

Basics of Python – Built-in Types Read More »

Basics of Python – Line Structure

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

Basics of Python – Line Structure

Line structure

A Python program is divided into a number of logical lines.

Physical and logical lines

A physical line is a sequence of characters terminated by an end-of-line sequence. The end of a logical line is represented by the token NEWLINE. A logical line is ignored (i.e. no NEWLINE token is generated) that contains only spaces, tabs, or a comment. This is called a “blank line”. The following code

>>> i=5 
>>> print (5)
5

is the same as:

>>> i=5; print (i)
5

A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as shown in the following example:

>>> if 1900 < year < 2100 and 1 <= month <= 12 \
. . .   and 1 <= day <= 31 and 0 <= hour < 24 \
. . .   and 0 <= minute < 60 and 0 <= second < 60 :
. . .   print year

A line ending in a backslash cannot carry a comment. Also, backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

>>> str=' This is a \
. . .    string example ' 
>>> str
' This is a string example'

Implicit line joining

Expressions in parentheses, square brackets, or curly braces can be split over more than one physical line without using backslashes. For example:

>>> month_names=['Januari','Februari','Maart',          # These are the
. . .    'April ', ' Mei ', 'Juni',                                              # Dutch names
. . .    'Juli','Augustus','September',                                 # for the months
. . .   'Oktober','November','December']                        # of the year

Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings; in that case, they cannot carry comments.

>>> str=" " "This is 
. . . a string 
. . . example" " "
>>> str
' This is \na string \nexample'
>>> str='' 'This is 
. . . a string 
. . . example'' '
>>> str
' This is \na string \nexample'

Comment

A comment starts with a hash character (#) that is not part of a string literal and terminates at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Also, comments are not executed.

Indentation

Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. This means that statements that go together must have the same indentation. Each such set of statements is a block. One thing that should be remembered is that wrong indentation can give rise to error (IndentationError exception).

>>> i=10
>>> print "Value is ",i 
Value is 10 
>>> print "Value is ",i 
File "<stdin>", line 1
print "Value is ",i 
∧
IndentationError: unexpected indent

The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens. One can observe that inserting whitespace, in the beginning, gave rise to the IndentationError exception.

The following example shows non-uniform indentation is not an error.

var=100 
>>> if var!=100:
. . .  print 'var does not have value 100'
. . .  else:
. . .                 print 'var has value 100'
. . . 
var has value 100

Need for indentation

In the C programming language, there are numerous ways to place the braces for the grouping of statements. If a programmer is habitual of reading and writing code that uses one style, he or she will feel at least slightly uneasy when reading (or being required to write) another style. Many coding styles place begin/end brackets on a line by themselves. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program.

Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the typical Python program. Since there are no begin/end brackets, there cannot be a disagreement between the grouping perceived by the parser and the human reader. Also, Python is much less prone to coding-style conflicts.

Basics of Python – Line Structure Read More »

Basics of Python – Operators and Operands

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

Basics of Python – Operators and Operands

Operators and operands

An operator is a symbol (such as +, x, etc.) that represents an operation. An operation is an action or •procedure that produces a new value from one or more input values called operands. There are two types of operators: unary and binary. The unary operator operates only on one operand, such as negation. On the other hand, the binary operator operates on two operands, which include addition, subtraction, multiplication, division, exponentiation operators, etc. Consider an expression 3 + 8, here 3 and 8 are called operands, while V is called operator. The operators can also be categorized into:

  • Arithmetic operators.
  • Comparison (or Relational) operators.
  • Assignment operators.
  • Logical operators.
  • Bitwise operators.
  • Membership operators.
  • Identity operators.

Arithematics operators

Table 2-2 enlists the arithmetic operators with a short note on the operators.

Operator

Description

+

Addition operator- Add operands on either side of the operator.

Subtraction operator – Subtract the right-hand operand from the left-hand operand.

*

Multiplication operator – Multiply operands on either side of the operator.

/

Division operator – Divide left-hand operand by right-hand operand.

%

Modulus operator – Divide left-hand operand by right-hand operand and return the remainder.

**

Exponent operator – Perform exponential (power) calculation on operands.

//

Floor Division operator – The division of operands where the result is the quotient in which the digits after the decimal point are removed.

The following example illustrates the use of the above-discussed operators.

>>> a=20 
>>> b=45.0
>>> a+b
65.0
>>> a-b
-25.0
>>> a*b
900.0 
>>> b/a 
2.25 
>>> b%a
5.0
>>> a**b
3.5184372088832e+58 
>>> b//a
2.0

Relational operators

A relational operator is an operator that tests some kind of relation between two operands. Tables 2-3 enlist the relational operators with descriptions.

Operator

Description

==

Check if the values of the two operands are equal.

!=

Check if the values of the two operands are not equal.

<>

Check if the value of two operands is not equal (same as != operator).

>

Check if the value of the left operand is greater than the value of the right operand.

<

Check if the value of the left operand is less than the value of the right operand.

>=

Check if the value of the left operand is greater than or equal to the value of the right operand.

<=

Check if the value of the left operand is less than or equal to the value of the right operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=20,40
>>> a==b
False 
>>> a!=b 
True
>>> a<>b 
True 
>>> a>b 
False 
>>> a<b 
True
>>> a>=b 
False 
>>> a<=b 
True

Assignment operators

The assignment operator is an operator which is used to bind or rebind names to values. The augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement. An augmented assignment expression like x+=l can be rewritten as x=x+l. Tables 2-4 enlist the assignment operators with descriptions.

Operator

Description

=

Assignment operator- Assigns values from right side operand to left side operand.

+=

Augmented assignment operator- It adds the right-side operand to the left side operand and assigns the result to the left side operand.

-=

Augmented assignment operator- It subtracts the right-side operand from the left side operand and assigns the result to the left side operand.

*=

Augmented assignment operator- It multiplies the right-side operand with the left side operand and assigns the result to the left side operand.

/=

Augmented assignment operator- It divides the left side operand with the right side operand and assigns the result to the left side operand.

%=

Augmented assignment operator- It takes modulus using two operands and assigns the result to left side operand.

* *=

Augmented assignment operator- Performs exponential (power) calculation on operands and assigns value to the left side operand.

//=

Augmented assignment operator- Performs floor division on operators and assigns value to the left side operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=20,40 
>>> c=a+b 
>>> c 
60
>>> a,b=2.0,4.5 
>>>c=a+b
>>> C
6.5
>>> c+=a 
>>> c
8.5
>>> c-=a 
>>> c
6.5
>>> c*=a 
>>> c
13.0
>>> c/=a 
>>> c 
6.5
>>> c%=a 
>>> c 
0.5
>>> c**=a 
>>> c 
0.25
>>> c//=a 
>>> c 
0.0

Bitwise operators

A bitwise operator operates on one or more bit patterns or binary numerals at the level of their individual bits. Tables 2-5 enlist the bitwise operators with descriptions.

Operator

Description

&

Binary AND operator- Copies corresponding binary 1 to the result, if it exists in both operands.

|

Binary OR operator- Copies corresponding binary 1 to the result, if it exists in either operand.

∧

Binary XOR operator- Copies corresponding binary 1 to the result, if it is set in one operand, but not both.

~

Binary ones complement operator- It is unary and has the effect of flipping bits.

<<

Binary left shift operator- The left side operand bits are moved to the left side by the number on the right-side operand.

>>

Binary right shift operator- The left side operand bits are moved to the right side by the number on the right-side operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=60,13 
>>> a&b 
12
>>> a | b
61 
>>> a∧b
49 
>>> ~a
-61 
>>> a< < 2
240 
>>> a>>2
15

In the above example, the binary representation of variables a and b are 00111100 and 00001101, respectively. The above binary operations example is tabulated in Tables 2-6.

Bitwise operation

Binary representationDecimal representation

a&b

00001100

12

a | b

00111101

61

a∧b

00110001

49

~a

11000011-61
a<<211110000

240

a>>200001111

15

Logical operators

Logical operators compare boolean expressions and return a boolean result. Tables 2-6 enlist the logical operators with descriptions.

Operator

Description

and

Logical AND operator- If both the operands are true (or non-zero), then the condition becomes true.

or

Logical OR’operator- If any of the two operands is true (or non-zero), then the condition becomes true.

not

Logical NOT operator- The result is reverse of the logical state of its operand. If the operand is true (or non-zero), then the condition becomes false.

The following example illustrates the use of the above-discussed operators.

>>> 5>2 and 4<8 
True
>>> 5>2 or 4>8 
True
>>> not (5>2)
False

Membership operators

A membership operator is an operator which tests for membership in a sequence, such as string, list, tuple, etc. Table 2-7 enlists the membership operators.

Operator

Description

In

Evaluate to true, if it finds a variable in the specified sequence; otherwise false.

not in

Evaluate to true, if it does not find a variable in the specified sequence; otherwise false.
>>> 5 in [0, 5, 10, 15]
True 
>>> 6 in [0, 5, 10, 15]
False
>>> 5 not in [0, 5, 10, 15]
False 
>>> 6 not in [0, 5, 10, 15]
True

Identity operators

Identity operators compare the memory locations of two objects. Table 2-8 provides a list of identity operators including a small explanation.

Operator

Description

is

Evaluates to true, if the operands on either side of the operator point to the same object, and false otherwise.

is not

Evaluates to false, if the operands on either side of the operator point to the same object, and true otherwise.

The following example illustrates the use of the above-discussed operators.

>>> a=b=3.1
>>> a is b 
True 
>>> id (a)
3 0 9 8 4 5 2 8 
>>> id (b)
30984528 
>>> c,d=3.1,3.1 
>>> c is d 
False 
>>> id (c)
35058472 
>>> id (d)
30984592
>>> c is not d
True 
>>> a is not b
False

Operator precedence

Operator precedence determines how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. In the expression x=7+3*2, x is assigned 13, not 20, because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Table 2-10 summarizes the operator’s precedence in Python, from lowest precedence to highest precedence (from top to bottom). Operators in the same box have the same precedence.

Operator
not, or, and
in, not in
is, is not
=, %, =/, =//, -=, +=, *=, **=
<>, ==, !=
<=, <, >, >=
∧, |
&
>>,<<
+, –
*, /, %, //
∼,+,-
**

Basics of Python – Operators and Operands Read More »