Python

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 »