Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Operators

Operators are special symbols that are intended to do some specific operations based on the values associated to it. Operators are categorized based on the type of intended functionality.

NotImplementedError

Triggered by abstract methods

StopIteration

Triggered by next() function to indicate that there is no further item to be returned by iterator

SyntaxError

Triggered by parser when syntax error is encountered

UnboundLocalError

Triggered when a local variable is referenced before its assignment

NameError

Triggered when a variable is not found in local or global scope

ReferenceError

Triggered when a weak reference proxy is used to access a garbage collected referent

RuntimeError

Triggered when an error does not fall under any other category

MemoryError

Triggered when an operation runs out of memory

while loop

while loop is a type of iterative statement which is a generic loop used when the loop pattern is known, loop has homogenous type of values and loop is sequential by nature. Most of the generic looping scenarios we would use typical a while loop. The above three components of the loop are to be explicitly defined in while loop. Syntax of while loop: Initialization while condition: looping statements here step value

Logical Errros

Logical Errors are those which are also occurred during the execution of the program but erroneous situations will not be visible like other errors. Most likely cause of Logical errors is due to wrong / bad coding practices. Logical errors can be identified and fixed by defining appropriate use cases which are functionality test checks.

Indentation

Indentation is used to group a set of statements together as block in Python. Where in other programming languages we may use curly parentheses or some keywords as begin, end of blocks. Python uses white space as an indented block and any un-indentation signifies the end of the current block. The Python style guide recommends using 4 white spaces as indentation level.

Built-in Exceptions

Built-in Exceptions in Python provides a number of classes which are used to deal with some of the predefined exceptions. Built-in Exceptions are those which are defined by the language himself and are implicitly executed when the expression triggers the error.

Compile time errors

Compile time errors are those type of errors which are occurred during the compilation of the program. Programmers cannot live with these errors. Most likely cause of the compile time error is syntax errors. These errors have to be fixed to continue the execution of the program. Compile time errors can be identified and fixed by knowing the programming language correctly and defining correct syntax.

List

List is an ordered set of mutable elements which are heterogeneous, dynamic and non-sequential by nature. Ordered here indicates the elements preserve their insertion order, heterogeneous indicate the elements can have any type of values stored, extensible indicates the memory can shrink or grown and dynamic indicates that every memory location is non-sequential or non-contiguous. A list object is represented with set of values enclosed within [ ] square parentheses. Label = [val1, val2, val3, val4,...,valn] to access the values of the list, we use indexes of the respective positions.

KeyboardInterrupt

Triggered when the user hits interrupt key (Ctrl+c or delete)

UnicodeEncodeError

Triggered when a Unicode-related error occurs during encoding

Delimiters

A delimiter is a sequence of one or more characters used to specify the boundary between to separate independent regions in expression or data representation. Delimiters are used in various representations of the Python language. They are used to build expressions, string literals, tuples, dictionaries, or lists.

Resolving name ambiguities

Many times there would be situations that encounters name collision of local functionalities in the program with the imported module functionalities and hence it becomes necessary to remove name collisions using aliasing mechanism without changing the original name of the functionality or the module itself.

Python Function Types

Python provides three types of function implementations; 1. Built-in function 2. User defined function 3. Anonymous function

for loop

for loop is a specific type of iterative statement which is used on domain of values. Domain is a group or set or collection of values. This type of loop is used when the loop has no pattern, loop has heterogeneous values, loop has no sequence. Most of the object iterations we would use for loop. for loops are faster and less overheads compared to while loop. The above three components of loop are implicit in for loop. for loop is characterized by the use of an implicitly referenced label wherein each iteration step a label is referencing to a value in given sequence or collection. This kind of for loop is mostly used in most of other programming and scripting. In Python there is no straight forward syntax for "do while" and "switch case" but programmatically we can achieve this. I would demonstrate "do while" and defer "switch case" for certain reasons.

What is Python?

"Python is a general purpose high-level, interpreted, interactive and high supportive of object oriented programming language". - Python is interpreted: This means in python everything is processed at runtime by the interpreter and you do not need to compile your program before executing it. - Python is Interactive: This means you can sit inside a python prompt and interact with the interpreter directly to write your code / implementations for understanding or get quick help. - Python is Object-Oriented: This means; python supports Object-Oriented style or technique of programming that encapsulates code within objects.

Python Program Structure

*Shebang line*: Shebang line is Unix like line which is used only in Unix and Unix type of environment to provide the path of the executing utility. It should be very first line in the executing program and has a special symbol which is combination of "#!" prefixed to the path of python. *Comments*: Comments are the descriptive statements which provides additional information of program here, which are further broken down as shown in screen shot. *Python Statements*: These are the language statements to perform specific intended purposes. Python does not need any line delimiter unless, multiple statements are given in single line.

File Handling Methods

*close()* Close the file handle which was opened *fileno()* Returns the file descriptor associated to the file *read()* Reads complete file if no parameter given *read(n)* Reads 'n' bytes from the current position *readline()* Reads the current file pointer line *readlines()* Reads lines into a list object *seek(offset, bytes)* Moves the file pointer to given bytes position using offset reference *tell()* Displays the current position of file pointer from beginning in bytes *write()* Writes the data into the file stream *writelines()* Writes set of lines into file stream

File modes

*r*: Open file in read mode and is the default mode if not specified. *w*: Open file in write mode, will overwrite the previous contents if file exist *a*: Open file in append mode, will append the contents to existing file at end

Benefits of Python

- Open Source - Software Testing & Automation - Desktop Development - Integration - Network Intensive Applications - Web Developments - Prototyping - Numeric and Scientific Applications - Application Scripting

Types of exceptions

1. Built-in Exceptions 2. User Defined Exceptions Built-in Exceptions are those which are defined by the language himself and are implicitly executed when the expression triggers the error. User defined exceptions are those which are defined by the user based on the business requirements and will be triggered based on the business scenarios. We would be not covering user defined exceptions due to other pre-requisites required.

Guidelines for Exception handling

1. Define only those likely exceptions which are tentative in the program 2. Define most likely exceptions on the top and less likely exceptions at the bottom 3. Define an exception object to capture the associated error message 4. Define non-technical and simple text message to display appropriate information to users regarding the errors 5. Define default exception handler to deal all undefined errors in the programs 6. Define nesting of exceptions do deal specific and generic exception and control of exception. 7. Group the exceptions to make it simple and provide more code clarity 8. Define program closure blocks to deal with program closure statements

Keywords

A keyword is a reserved word which are intended to do some specific operations. Keywords are used to perform a specific task within a computer program. A programmer should not use a pre-defined keyword for any other references or as an ordinary identifier. Examples: and elif if print as else import raise assert except in return break exec is try class finally lambda while continue for not with def from or yield del global pass

Grouping of exceptions

Grouping of exceptions would be recommended to make the program to have more code clarity and the code representations better. #! /usr/bin/python try: x = input("Enter first number : "); y = input("Enter second number : ") print "The values stored are ", x,y res = x / y print "The result of two divided numbers are ",res except (ZeroDivisionError, TypeError, NameError), e: print "Error occured : ", e except Exception,e: print 'Default Exception caught: ', e

File Handling: Open

Before the file operations are done, File has to be associated to the program for either of the said operations. Open function is used to specify the file handle for the required operations. Open function will create a handle / association of the physical file to the temporary memory. filehandle = open ('filename', 'mode', [buffering]) The open function takes three parameters, a. Filename b. Mode c. Buffering *Filename*: The name of the file which needs to be associated to the program. *Mode*: Mode is an optional argument. The type of operation intended on the file to be specified. If the file needs to only read / open the contents to be used without any changes, then open in 'r', If the file has to be opened with write / modification operations possible then we open with write mode. But write mode will erase the previous contents of the file. The file can be also opened with append mode 'a', which will allow users to append the new contents to be written into the file at the end of the current file without deleting the previous contents. *Buffering*: Buffering argument is optional which specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

Command Line Arguments

Command line syntax: <command> [-options] <ProgramName> [<arguments>] Command in the above syntax is the executing utility Options in the above syntax are used to fine tune program execution ProgramName in the above syntax is the file which contains the instructions to be executed Arguments in the above syntax are the necessary values provided in hand to program File Handling ### File handling is a mechanism to store, retrieve and manipulate the program generated data permanently into storage device and can be loaded back to program by populating data into various data structure object for internal purposes. Python has many built-in functions to perform file operations. open (), for opening a file on disk. open returns a file object, which has methods and attributes for getting information about and manipulating the opened file. There are two key file operations to be performed before the data is either to be stored or retrieved. 1. Read Operation 2. Write Operation

Conditional Control Statements

Conditional control statements are those wherein conditions are the mechanism to control the flow of execution and execute a block of statements as required. In Python we have only "If" conditional control statements as Python internally works only on references and hence "Switch Case" statements of other high level programming languages would not make any much difference than using "if ladder style". There are four styles of if conditional control statements a. Bare if is used to execute a block of statement only if the condition is true and ignore if the condition does not satisfy. b. If else is used to execute a block of statement relating to if the condition being true and else execute another block of statement if the condition does not satisfy. c. If nested is used when multiple levels of conditional statements are to be checked and executed. Simple we can term if nested as "if" conditional statement within another "if" conditional statement. d. If ladder is used to specify multiple conditional statements to be given with multiple optional values which could execute the relative option as matched with the given criteria and terminate.

Data Structure Objects

Data structure is a mechanism to provide a necessary layout and organize data which could be stored easily and retrieved quickly based on the intended purpose. Python supports extensible structured types without any need to do a workaround like pointers references, or even worse things like explicit type-casts with structured objects though the type casting is available in Python which is purely for specific business requirements. There are many built in Data Structure elements present in python and we would be discussing with only three of the main types; a. List b. Tuple c. Dictionary

Basic Datatypes

Data types are the type specification given to the reserved memory location to store some compatible type of required values. In python for easy understanding datatypes can be categorized as; a. Primitive Type b. Non Primitive Type

Default exception

Default exception block will handle all the unhandled exceptions in the program and has to be defined only at the end of all exceptions. #! /usr/bin/python try: x = input("Enter first number") y = input("Enter second number") print "The values stored are ", x,y res = x / y print "The result of two divided numbers are ", res except ZeroDivisionError, e: print "You are trying to divide by zero" except NameError, e: print "You are trying to access a label which is not defined" except Exception, e: print "Default Exception handled: ", e Program closure statements ### Program closure statements are those which will get executed just before terminating the program. There are two types of program closure statements as blocks. 1. finally 2. else *finally* block will get executed anyhow, whether if any error is thrown or not in the program and then the defined finally block will get executed. *else* block will get executed only if there is no error in the program and the else block gets executed. The program closures should be only defined along with try block only. #! /usr/bin/python try: x = input("Enter first number"); y = input("Enter second number") print "The values stored are ", (x,y) res = x / y print "The result of two divided numbers are ",res except ZeroDivisionError: print "External: You are trying to divide by zero" except NameError, e: print "External: Error with the value given to program" else: print "Else: I execute only if the error is not thrown in program" finally: print "Finally: I will be executed all the times, irrespective of error thrown or not"

Dictionary

Dictionary is a type of Data structure object in python which is unordered and mutable object represented with a pair of representation as key and value. Dictionary is also known as hashes, associative arrays etc., in other programming languages. Dictionary is a mechanism to bind the index value (key) to associate element (value) which was a challenge to store earlier. Eg. If we would like to store Population of different countries / Headcount of various location of Wipro we can use Dictionaries. Keys are like indexes which are unique by nature and the associated element will be stored as value for the key. Dictionary can be represented with {} parentheses. The representation for dictionary should be always in pair of representation as key and value. Label = { key1 : value1 , key2 : value2, key3 : value3, .... keyn : valueN} The insertion order is not preserved in case of Dictionary. To access the values of the dictionary, we use keys and the respective values of the given key positions are returned. There are couple of methods in dict class which can be applied on dictionary object, of which some are; keys (): This returns a list object which is going to contain the keys present in the dictionary object. values (): This returns a list object which is going to contain the values present in the dictionary object.

Features of Python

Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the user to understand the language in a relatively short period of time Easy-to-read: Python code is much more clearly defined and visible Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and other OS Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code Portable: Python can run on a wide variety of hardware platforms and OS which has the same interface on all platforms. Extendable: You can add built in and third party modules to the python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable: Python provides a better structure and support for large programs than any other scripting and highly scalable.

Exception Handling

Errors are the events that are triggered during the execution of the program, which are unexpected and abnormal. If error occurs, then it halts the execution of the program any further, checks if any exception handling blocks are defined, if so it then transfers the execution control to the matching exception in the block and then terminate the program. If exception handling block is not defined in the program, then the control is transferred to built-in exception list where the language himself will take care of executing appropriate exception handler. Exceptions are mechanism to deal with errors which are encountered in the program during the execution of the program. Errors can be categorized as; 1. Compile time Errors 2. Run time Errors 3. Logical Errors

Identifiers

Identifiers in python can be created using alphanumeric characters and also use of underscore _ character to separate multiple words. A variable name should not begin with a number and not recommended to have any keyword as names. Python language provides style guide for naming conventions and other language specifications found in the style guide of PEP documentation in python.org.

Python Exception Handling

In python we deal with only Runtime errors and we call them as Runtime exceptions. Exceptions in python can be handled with try and except keyword block definitions. If exceptions are handled in the program, the program anticipates the defined type of errors and if encountered will halt the execution and transfer the control to the appropriate exception handler and smoothly terminate the program. It is a good practice to deal with errors by defining exceptional handling. There are two component of Exception; a. Exception handle b. Exception message Exception handle is one through which the exception is referenced. In python every exception handle is a class. Exception message is the information provided to understand the cause of the error. Handling exception is not a mechanism to solve the problem but to make the program termination smooth and as anticipated.

Literals

Literals are the values which are associated to the reserved memory locations that are stored in it. There are different types of literal classifications, which are termed as Data type.

Loop Control Statements

Loop control statements are iterative statements which are executed for known number of times. Whenever there is a requirement to execute a bunch of statements repeatedly for finite number of times, looping statements come in handy. Looping statements are iterative statements which are executed for known number of times. There are two types of looping statements in python; 1. while loop statement 2. for loop statement Either of types of loops has three components for construction; a. Initial Value / Start value b. Condition / Final Value c. Step Value / Increment / Decrement

List methods

Method is a member of class that defines a behavior or functionality required and can be applied to an object of the class where method belongs to. append(): This method is used to insert value at the end of list object. append takes single / one group value as applicable. Eg. listobject.append(value) count(): This method returns the number of times the value is found in the given list object. Eg. label = listobject.count(value) extend(): This method is used to add multiple values of any iterable object arbitrarily at the end of the list. Eg. listobject.extend(otherlistobject) index(): This method returns the index of first successive search of the given element if found in the list object. Eg. label = listobject.index(value) insert(): This method is used to insert a value anywhere between the list object. It takes two parameters where the first one is offset (postion / index) value, and second is the actual value to be inserted. Eg. listobject.insert(index,value) pop(): This method is used to return and remove the last element found in the list object if no parameter given, if the parameter given as an index, it will return the given index position value and also remove from the listobject. Eg. label = listobject.pop([index]) reverse(): This method is going to flip the list, which means the last element becomes first and the first element becomes last as the order and so as other subsequent elements in the list object will be placed. Eg. listobject.reverse() sort(): This method is going to sort the elements in the list in ascending order and apply the changes to the same object. Eg. listobject.sort() Range Function: Range is a function in python which is returns a list object containing range of values within the given limits and can be used to generate lists quickly. Range function takes three parameters. range([startvalue], stopvalue, [stepvalue]). If start value is not given, it takes default start value as zero. If step value is not given, it takes default step value as 1. stop value is mandatory which always specify the end of list, and this value will not be considered for the values in list. It always takes one prior to the last value. [ ] is referred as a range operator and is used to extract values from a list object given as [startvalue: stopvalue: stepvalue], here also startvalue and stepvalue is optional.

Setting up Module Search Path

Module search path is the locations where python interpreter would search for the importing module files. If the user defined module file exist anywhere outside this default search path, then we should include the exact location within the module search path. Earlier we had created both the Module body file and Module use file in the same directory which would not be the case in real time scenarios. Modules can be made available to access anywhere across the storage repository. If the source program and the Module program file does not exist in the same directory, then it is necessary to include the module search path in the following ways. There are two ways to set the module search path. 1. Platform level 2. Script level To define the module search path at the platform level, we create a Python environment variable called PYTHONPATH and include the module search path to look for the defined modules. To define the module search path at the script level the python provides a built-in list object inside sys module called path. This list object will be used by Python to search the module path when import statement is defined with module use file. We have to import sys module and append the new search path into the path object. It is left to programmer's choice to decide defining style of module search path. Platform definition: To define python path at the platform level, user needs to have admin access to the system and follow the screen shot to define the PYTHONPATH variable. PYTHONPATH variable is recommended to be created within the USER SECTION of environment variable since the variable is only used by current user and becomes appropriate to individuals.

Modules

Modules are mechanism in Python to group a set of functions having similar goal or functionality as a separate file which can be included within any other program for reusability and concurrent access of the defined functionalities present in the modules. Functions are local to program, whereas Modules can be extended to any other external program where the functionalities can be consumed. Modules are also mechanism in Python to secure the source code by implicitly Python himself compiling the module program into byte code representation and this byte code can execute on any platform and is non-human readable which understood only by python interpreter himself. Module files should have mandatory an extension of somename.py, and therefore any Python program can act as a module file if it satisfies the rules. Modules mostly contains two components; 1. Function definitions 2. Data Members There are two types of Modules; a. Built-in Modules b. User Defined Modules

Non Primitive Data Types

Non primitive types are Data structure type representation; There are many such objects with some underlying Data structure implementations, some are mentioned; a. List b. Tuple c. Dictionary d. Sets e. Datetime

Operators

Operators are special symbols which are intended to do some specific operations based on the values associated to it. Operators are categorized based on the type of intended operations. Operators are categorized based on the type of intended operations and associated with the value types are as follows; a. Arithmetic Operators are those which are intended to do specific mathematical operations like Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%) and so on. b. Logical Operators are those which are used to perform logical binding of two or more conditions using "and", "or" and "not" logical operators. c. Relational Operators are those which are used to perform condition based execution which returns True or False. d. Shift Operators are those which performs shifting of bits in the internal representations for computing new values. e. Membership Operators are those which are used to find the membership associations within values or objects. f. Bitwise Operators are those which are used to perform bitwise operations for internal computations.

Primitive Date Types

Primitive types are those which are the simple types and store mostly unary values in it. Non primitive types are those which are extension of simple types to store multiple values. In Python any type of value will stored internally as an object type only. Primitive types can be further broken down as; 1. Number type 2. Non Number type Number data types can be further categorized as a. Integer: This can store integer type of values which can be a signed number b. Floating: This type can store floating number type of values c. Complex: This type can store complex type representations numbers d. Long: This can store long integers and they also can be represented in octal and hexadecimal forms Non number data types could be a. Strings: This can store set of characters or any raw text b. Boolean: This can store True or False as Boolean values c. None: This type of representation indicates non-existent, not known or empty values or can be treated similar to NULLs in other programming language

Default Values

Python supports the use default values within a function block to have a reserved value that can be used, if the required values are not passed within the function call. It is also beneficial to use default values to suite with varied parameter requirements for internal computations.

File Handling: Read Operation

Read operation will load the associated given physical file contents into temporary area reading the contents from the secondary storage to primary storage, which we can use within the python program. Read operation does not allow the user to make modifications to the opened file or the data associated to it.

Recursive Functions

Recursion is the programmatic approach of calling a function within self with changing value sets. Recursive style help programmer to design simpler and code clarity. It would be beneficial to use recursive functions for recursive data structures (like trees) or recursive algorithms.

Run time errors

Run time Errors are those which are occurred during the execution of the program. Programmers can live with these errors still being there. Most likely cause of Run time errors would be wrong / bad / inappropriate data representation, the program will have no challenges for compilation but would encounter error only if bad data. Run time errors can be identified and fixed by defining appropriate test cases to check the data validation.

Scope

Scope defines the availability of any member within any defined memory block or boundary of code. There are three type of scopes which can be defined in Python as; 1. Local Scope 2. Global Scope 3. External Scope *Local scope* are those members; in which these members are only available within a specific defined block. If we define any members within a function, we can say its scope is localized within the defined function. *Global scope* are those members; in which these members are available anywhere across the program. If we define any members within the main block of the program which is also the default block where the execution starts available in a built-in namespace "__main__", then we say the member is within a global scope. *External scope* are those members; in which these members are defined in other external programs and are accessed within any other program. Members in other external files defined such as modules, packages, classes can be treated as external scope. These members can be used by importing / including the files within any source program.

Steps to create user defined Modules:

Step 1: Create any file with a good naming convention and must have .py as file extension, this is module body file. Step 2: Edit the created file and define all the required functionalities into the body file intended for your business requirement. Step 3: Create another file as a source program which will consume the defined functionalities in the module body file (This will be consuming file). Step 4: Define appropriate import statements to include the required module body file into the module use file as required. Step 5: Use fully qualified naming convention to access the defined module functions as modulename.functionname(). Step 6: Execute the module source file, which in turn will compile the module body file and creates a new file which is the byte code file having samename.pyc called python compiled code. Step 7: Move this .pyc byte code file to the storage repository for concurrent access and code reusability.

Steps to create Python Package

Step 1: Create any folder with a good naming convention, which will act as a package. Step 2: Get inside this created folder and start adding the module files which are to be part of package. Step 3: Create a special file __init__.py which is called package constructor necessary for package construction to define and integrate the module files. Step 4: Edit this package constructor file and define appropriate import statements inside this __init__.py file. Step 5: Repeat the step 2, step 3 and step 4, if there are any sub packages to be created under the main package to increase the modularity. Step 6: Come outside of root package folder and create a package source file which will consume the package members. Step 7: Use appropriate import statement defined in the package use file to access the package members using fully qualified naming conventions like packagename.modulename.specificfunctionalities. Step 7: After successful compilation only retain the .pyc files and move out .py files from the folder structure.

Control Statements

There are two types of control statement within python; a. Conditional Control statement b. Loop Control statements

User defined Functions

These are defined by the programmer based on the business requirement and will be available locally across within the same program. User defined functions are those which are created by the programmer based on the business requirements. There are two of User defined components of functions. a. Function Body b. Function Call *Function Body*: Function body defines the actual code which needs to be executed at any specific requirement. In Python the body of function has to be defined first in the program before the function is getting called. Function body can be defined using a keyword "def" prefixed in front of given function name. *Function call*: Function call will transfer the control of current execution into the respective namespace / function body and executes the code defined within the function body. Once the function completes the execution the control would return back to the calling environment.

Anonymous Functions (lambda)

These are functional blocks without any name. These are used to reduce the overheads caused in traditional style functions and does code replacement like the macros in C programming. Anonymous functions are those which does not have any function name but they are used to reduce functional overheads which are frequently called having a single line execution.

Built-in Functions

These are provided by the python language himself with a predefined functionality. These functional blocks are always available throughout the program code. Python has many predefined functionalities as built-in function which are given by Python himself to suite day to day activities and can be used as per business requirements. These built-in functions are always available to every program without explicitly including it within program. The following table provides the list of built-in functions provided by Python himself; Python's built-in functions are grouped into a special module called __builtins__ named internally as __builtin__. It also contains other members like exception classes and other built-in data members. Python imports all the "built-in" functions into the namespace when the interpreter is loaded so that programmer can use them directly anywhere in the program.

Built-in Modules

These are the modules provided by the Python language himself having a group of predefined functionality within it. These are not always available to the program code; it has to be included into the program using import statement. We can list out the available built-in modules using help('modules'), this will list out the version specific modules which are integrated along with the current version of software itself. Modules can be included into the program by using import statement, and import can be applied in three styles. a) import module1, module2, module3,..., module b) from module import * c) from module import specific1, specific2,....,specific n Listing the members of the namespace using dir() function. dir() is a built in function which is used to return a list object containing the members of the current working namespace.

User Defined Modules

These are types of module which is defined by the programmer himself based on the business requirement and can be made available within a program by including it using import statement. When complexity of application grows and if many functionalities are required to be defined a part of application and make these functionalities to be concurrently accessed by other files and also other users, it would be good to separate the function definitions and their implementations. Modules are organized way of defining relative functionalities and grouping them together in a single file. We would require user defined modules for three key purposes. 1. Modularity 2. Reusability 3. Security Modularity will improve the code representation by breaking down a large program into smaller components as modules which can be pluggable to any program wherever the defined functionality is required. This improves the Reusability of the functionality without re-writing the code again and again and can be accessed concurrently from the stored repository. Python creates a special file which is non-human and can be only interpreted by the Python interpreter adds Security to the Module file. User defined modules refer to a Python file having only function definitions and no other standalone statements within it. Module body file contains only function definitions and its data members and this file can be used by other programs and consumed as Module use by importing it, instead of copying their source code into different programs. To provide security to module files, Python creates a non-human readable code which is called Python byte code which secures your module file and this can be shared across users without revealing the code stored in central repository. Python byte code is created by Python himself when the import statement is used on any module file and this creates a .pyc file which called as Python Compiled file. This file can be pushed to a storage repository for Concurrent access and Code reusability.

SystemExit

Triggered by sys.exit() function

UnicodeError

Triggered when a Unicode-related encoding or decoding error occurs

UnicodeDecodeError

Triggered when a Unicode-related error occurs during decoding

UnicodeTranslateError

Triggered when a Unicode-related error occurs during translating

FloatingPointError

Triggered when a floating point operation fails

ValueError

Triggered when a function gets argument of correct type but improper value

TypeError

Triggered when a function or operation is applied to an object of incorrect type

GeneratorExit

Triggered when a generator's close()method is called

KeyError

Triggered when a key is not found in a dictionary

AssertionError

Triggered when assert statement fails

AttributeError

Triggered when attribute assignment or reference fails

TabError

Triggered when indentation consists of inconsistent tabs and spaces

IndexError

Triggered when index of a sequence is out of range

SystemError

Triggered when interpreter detects internal error

OverflowError

Triggered when result of an arithmetic operation is too large to be represented

ZeroDivisionError

Triggered when second operand of division or modulo operation is zero

OSError

Triggered when system operation causes system related error

ImportError

Triggered when the imported module is not found

EOFError

Triggered when the input() functions hits end-of-file condition

IndentationError

Triggered when there is incorrect indentation

Tuple

Tuple is another Data structure object which is like list but having a read only property. Tuple is an ordered immutable object, which does not contain any methods. This is like read only list. Any time if user needs to create a set of items which is constant by nature, then tuple would be a choice to create. tuple is represented with () parentheses. The values once inserted to tuple cannot be modified in anyway. So tuples are read only list. Tuplelabel = (val1, val2, val3,....., valn) The value extract could be similar to list and can be accessed using the index positions.

Variables

Variable can be categorized by nature of its implementation as two types; 1. *Implicit variables* are those which are defined and used within the program without any exclusive declarative statement. Mostly this type of variable is used within Scripting languages to provide a greater flexibility to storage of values. The type specification of value is declared / specified internally by the language himself based on the associated value in the reserved location. 2. *Explicit variables* are those which are declared, defined and then used within the program having an exclusive declarative statement. With this style of defining, the type specification is fixed for the variable throughout its life and cannot change its type. Mostly this type of variables is used in high level programming languages. In python variables are referred as *labels* which are just reference or identifier to values stored. In python everything works on references only.

Components of Variables

Variable is a reserved memory location which is intended to store some type of value in it. There are two components of any variable; 1. Literal 2. Identifier Literals are the values associated to any reserved location and identifiers are the associated names through which these stored values are accessed.

Variables

Variables are reserved memory locations which are used to store some intended type of value in it. In python variables are termed as labels which are references to the value, which are actually stored in the reserved locations. In python everything works on references only.

Packages

When complexity of application grows and if many modules are required to be defined for the application, managing and representation becomes difficult. Packages are mechanism in Python to create hierarchical grouping of module files having similar goal or functionality or integrate module for application as folders which can be included in any program for reusability and concurrent access. Package pack module files together providing a single interface and separates the design and code. Packages mostly contain module files and also a special file called package constructor having the name __init__.py file in every folder of the package level. This package constructor file contains appropriate import statements to include the module files as part of package. Packages can be either a flat package or hierarchical package.

File Handling: Write Operation

Write operations will dump / write the program temporary data contents from temporary memory to secondary storage device as a physical file which was associated during the opening and will support any manipulation of the contents in the physical file.


Set pelajaran terkait

E3 Capitalism Entrepreneurs Mercantilism banking system finance laissez fiare capitalism Adam Smith Industrial Age

View Set

Green Line New Bayern 6 Topic 1 My child is starving...

View Set

FIN 3403 Exam 3 - Conceptual (Ch 12)

View Set

Managing Receivables and Payables to Improve Cash Flow Activities

View Set

Pään lihakset (miimiset lihakset hermotus n. Facialis)

View Set

Chapter 9 - Pain (The 5th Vital Sign)

View Set

CHAPTER 4: STATES OF CONSCIOUSNESS

View Set

Module 43(Schizophrenia & Other Disorders)

View Set

OB Chapter 42; The Child with Cardiovascular Dysfunction

View Set

Ani Class 2 EVS Lesson 10. Animals

View Set

Lane Travel—Maintaining a Space Cushion

View Set

Control of Ventilation: Chemoreceptors and Chemical Reflexes.

View Set