Python tutorial - Introduction to Python

download Python tutorial - Introduction to Python

of 104

description

A presentation covering introduction to Python language.

Transcript of Python tutorial - Introduction to Python

Python for beginners Session for B.Tech COE-V Sem. 2013-14

Python for beginnersSession for B.Tech COE-V Sem.2013-14

Part IIntroduction to Python. A Theoretical overview of evolution.Part IIThe technical aspects and coding standards. Learning Python.Part IIIAdvanced features of Python.Part IVExpectations from target audience.

Session Roadmap -Need for Python.History of Python definitionCharacteristics of the languageFeaturesUsesComparative study with similar languagesPython and the coming future.

Part INeed of a language that was easy to read and use.At the Same time also fulfilling the requirement of a language to be object oriented.Need of an highly extensible language that can be embedded in to existing applications.Need of an alternative to traditional available languages, so that new opportunities can be explored.

WHY PYTHON WAS NEEDED?HISTORY OF PYTHONPython was developed by Guido Van Rossum in the late 80s & 90s at national research institute for mathematics and computer science in netherlands.

Guido van Rossum Developed as a successor to the ABC language and was capable of exception handling and integrate with Amoeba operating system. Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages.

WHAT IS PYTHON ?Python is Interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP.Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs.Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects.Python is Beginner's Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

Characteristics of Python :Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

It is Dynamically typed, object-oriented Language.

Runs on Win, Linux/Unix, Mac, OS/2 etc.

Versions: 2.xand 3.x

Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.

Easy-to-read: Python code is much more clearly defined and visible to the eyes.

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 Macintosh.

Python featuresInteractive 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 has the same interface on all platforms.

Extendable: You can add low-level 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 shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below:Support for functional and structured programming methods as well as OOP.It can be used as a scripting language or can be compiled to byte-code for building large applications.Very high-level dynamic data types and supports dynamic type checking.Supports automatic garbage collection.It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.

ScriptingRapid PrototypingText ProcessingWeb applicationsGUI programsGame DevelopmentDatabase ApplicationsSystem AdministrationsAnd many more.

What can Python do?

Rapid prototyping is a group of techniques used to quickly fabricate a scale model of a physical part or assembly using three-dimensional computer aided design (CAD) data.Construction of the part or assembly is usually done using 3D printing or "additive layer manufacturing" technology.Rapid prototypingIn computing, the term text processing refers to the discipline of mechanizing the creation or manipulation of electronic text. Text usually refers to all the alphanumeric characters specified on the keyboard of the person performing the mechanization, but in general text here means the abstraction layer that is one layer above the standard character encoding of the target text. The term processing refers to automated (or mechanized) processing, as opposed to the same manipulation done manually.Text processingIn computing, a web application is any application that uses a web browser as a client.[1][2] The term may also mean a computer software application that is coded in a browser-supported programming language (such as JavaScript, combined with a browser-rendered markup language like HTML) and reliant on a common web browser to render the application executable.Web applicationIn computing, graphical user interface is a type of user interface that allows users to interact with electronic devices through graphical icons and visual indicators such as secondary notation, as opposed to text-based interfaces, typed command labels or text navigation. GUIs were introduced in reaction to the perceived steep learning curve of command-line interfaces (CLI), which require commands to be typed on the keyboard.

guiGame development is the process of creating a game. Development is undertaken by a game developer, which may range from a single person to a large business. Traditional commercial PC and console games are normally funded by a publisher and take several years to develop. Indie games can take less time and can be produced cheaply by individuals and small developers. The indie game industry has seen a rise in recent years with the growth of new online distribution systems and the mobile game market.Game developmentA database application is a computer program whose primary purpose is entering and retrieving information from a computer-managed database. Early examples of database applications were accounting systems and airline reservations systems, such as SABRE, developed starting in 1957.Database applicationsA system administrator, or sysadmin, is a person who is responsible for the upkeep, configuration, and reliable operation of computer systems; especially multi-user computers, such as servers. He seeks to ensure that the uptime, performance, resources, and security of the computers he or she manages meet the needs of the users, without exceeding the budget.

system administrationAreaPerlRubyPythonReadabilityBadGoodGoodObject OrientedNoYesYesDebuggingGoodBadGoodComputation speedGoodBadOkComplexityLowHighHighStandardizedNoYesNoFail Safe ExceptionsNoYesYesPython vs. rest of the world -Program execution slower than java but are 3-5 times shorter than Java and 5-10 shorter than C++ and thus take less time to develop.

Python vs Java & C++Python vs JavascriptNearly equivalent but supports writing much larger programs and better code reuse through a true object-oriented programming style, where classes and inheritance play an important role.

Python and futurePython is easy for analysts to learn and use, but powerful enough to tackle even the most difficult problems in virtually any domain. It integrates well with existing IT infrastructure, and is platform independent. Among modern languages, its agility and the productivity of Python-based solutions is legendary. Companies of all sizes and in all areas - from the biggest investment banks to the smallest social/mobile web app startups - are using Python to run their business and manage their data.Python for Big datahttp://www.python.org/getit/http://www.python.org/getit/releases/2.6.6/http://www.stat.ucla.edu/~rosario/classes/07F/202a/python/http://www.download366.com/python?utm_source=google&utm_medium=cpc&utm_campaign=366_IN_Otros&utm_content=Python&utm_term=download%20pythonhttp://en.wikipedia.org/wiki/Python_%28programming_language%29http://www.tutorialspoint.com/python/

Source materialPart II - RoadMapInstallation ProcedureProgramming Modes and other rulesData TypesOperatorsConditional HandlingIteration handlingMathematical FunctionsString FunctionsList and Dictionary functionsUser defined functionsThe current production versions are Python 2.7.6 and Python 3.3.3. Download it from official website.This site hosts the "traditional" implementation of Python (nicknamed CPython). A number of alternative implementations are available as well, namelyIronPython (Python running on .NET)Jython (Python running on the Java Virtual Machine)PyPy (A fast python implementation with a JIT compiler)Stackless Python (Branch of CPython supporting microthreads)Other parties have re-packaged CPython. These re-packagings often include more libraries or are specialized for a particular application.

Installation ProcedureINTERACTIVE MODE PROGRAMMING

Interactive mode means invoking the interpreter without passing a script file as a parameter.

Type print command on the right side of the prompt : Output will be :

Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished.Write your python program in a script. Save the file with .py extension.

SCRIPT MODE PROGRAMMING

Now on cmd, change the path to your script location using cd command.Then write command : py test.pyOutput will be :PYTHON IDENTIFIERSName used to identify a variable, function, class, or any other object. Starts with a letter or an underscore(_), followed by zero or more letters, underscores or digits. Python is a case sensitive language. So identifiers a and A are considered to be two different identifiers. Special characters like @, $, % are not allowed within identifiers. Reserved keywords cannot be used as identifiers. List of reserved words in python :

No braces to indicate blocks of code. Blocks of code are denoted by line indentation. All the statements within one block must be indented the same amount of spaces. For example, following is a correct code :

LINES AND INDENTATION

MULTILINE STATEMENTS Use continuation character (\) to indicate that the line should continue. For example :

Do not have to be explicitly declared.Declaration happens automatically while assigning value to a variable. For example : VARIABLE

Possible to assign a single value to multiple variables. For example :

Five standard data types :NumberStringListTupleDictionaryNumber :Support four different numerical types :Int (Signed integers)Long (Long integers)Float (Floating point values)Complex (Complex number)For Example :

STANDARD DATA TYPES

Strings :Subsets of strings can be taken using slice operator ([ ] or [ : ]).Plus (+) sign is used as concatenation operator.Asterisk (*) sign is used as repetition operator.For Example :

Lists : Compound data type. Contains items of same or different data types. Plus (+) is used as concatenation operator. Asterisk (*) is used as repetition operator.For example :

Tuples : Similar to lists. Elements are enclosed within parentheses. Can be considered as read-only list. Elements cannot be updated and size cannot be modified.

Dictionary : Hash table type. Consists of key-value pairs. Enclosed by curly braces ({ }).For example :

DATA TYPE CONVERSIONBuilt-in functions to perform type conversion.

OPERATORSArithmetic Operators :

Comparison Operators :

Assignment Operators :

Bitwise Operators :

Logical Operators :

Membership Operators :

Operator Precedence :Following table represents operators from highest precedence to lowest.An example of operators :

DECISION MAKINGDecision making statements supported by Python :

An example :

LOOPS Loops supported by Python :

Loop Control Statements Used to change normal execution sequence. Control statements supported by Python :

MATHEMATICAL FUNCTIONS

TRIGONOMETRIC FUNCTIONS

MATHEMATICAL CONSTANTS

For Example :STRING SPECIAL OPERATORS

BUILT-IN STRING METHODS

Example :BUILT-IN LIST FUNCTIONS

Example :

BUILT-IN DICTIONARY METHODS

Example :

FUNCTIONS Block of organized, reusable code. Block begins with keyword def followed by function name and parentheses (). Code block within every function starts with a colon (:) and is indented. Return statement is used to exit from a function. Arguments are passed by reference in Python. Keyword arguments allow to pass parameters out of order. Example :

Default parameters are also supported. Example :

Part III The Tunnel aheadPython modules and namespacesUser Inputs and OutputsFile I/OPartial FunctionsException HandlingObject Oriented approach and Python

A Python module is as simple as a function kept in file for purpose of reuse.Modules are necessary to handle larger applications.Create functions in a .py file and save it.Using Modules-import module_name.module_function();from import *module_function();Python ModulesThis module represents the (otherwise anonymous) scope in which the interpreters main program executes commands read either from standard input, from a script file, or from an interactive prompt.When a program is executed directly _name_ is set to _main_Executing the python file directly means the main() command will be searched for.if __name__ == "__main__": main()One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module.

Special Variables : _name_Provided for efficiency or to provide access to operating system primitives such as system calls.sys module sys.path - The variable sys.path is a list of strings that determines the interpreters search path for modules.dir() function - returns a sorted list of strings of variables, modules, functions inside a module.Standard ModulesWhats in a name?A name in Python is roughly analogous to a variable in just about any other language, but with a few extras. name can be of variable,list,dictionary and even funciton likedef func():f=func;Python NamespacesA namespace, is obviously enough, a space that holds a bunch of names. they are a mapping from names to objects.it as a big list of all the names that youve defined, either explicitly or my importing from modules. Its not something than you have to create, its created whenever necessary.A module is simply a file containing Python code. This code can be in the form of Python classes, functions, or just a list of names. Each module gets its own global namespaces. So you cant have two classes or two functions in the same module with the same name as they share the namespace of the module.Python NamespaceWhenever you run a simple Python script, the interpreter treats it as module called __main__, which gets its own namespace. The builtin functions that you would use also live in a module called __builtin__ and have their own namespace.Python Namespaceimport SomeModule This is the simplest way to do imports and generally recommended. You get access to the modules namespace provided you use the modules name as a prefix. This means that you can have names in your program which are the same as those in the module, but youll be able to use both of them. Its also helpful when youre importing a large number of modules as you see which module a particular name belongs to.Importing and namespaces2. from SomeModule import SomeNameThis imports a name (or a few, separated by commas) from a modules namespace directly into the programs. To use the name you imported, you no longer have to use a prefix, just the name directly. This can be useful if you know for certain youll only need to use a few names. The downside is that you cant use the name you imported for something else in your own program.Importing and namespaces3. from SomeModule import * This imports all the names from SomeModule directly into the modules namespace. Generally not a good idea as it leads to namespace pollution. If you find yourself writing this in your code, you should be better off with the first type of import.Importing and namespacesas a run time parameteruser input passed as an argument while running the script.ex- test.py helloand accessing the parameter as sys.argv[1]

import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv)User Input - Way 1raw_input() takes user input as a string type.input() equivalent to eval(raw_input()) and is used to evaluate regular expressions. Python 2Python 3 has input() returning user input as string only. raw_input() is deprecated.User InputTraditional use of % and problem of % with tuples.str.format() method.typecasting values to string by str().str()=user readable form.repr()= interpreter readable form.print("we are the {0} of {1}".format('students','NSIT'));print({key1}{key2}.format(key1:val1,key2:val2));format functions to use time and set decimal offsets is more human readable.Output Formattingopen() returns a file object, and is most commonly used with two arguments: open(filename, mode,[buffersize]).Use of with ensures immediate file closing after reading it.with open("myfile.txt") as f: for line in f: print line,most commonly used modes-r=read (default if not specified)w=writea=appendb=binary (platform independence)r+ = read and writew+ =read and write but overwrites existing file.

FILE I/Obuffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).every file has attributes like file.closed, file.mode, file.nameclose() method - The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

File I/Oread() Method fileObject.read([count]);passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

It returns an empty string at the end of file.readline() Method-reads a single line from the file with an appended newline character. returns an empty string, the end of the file has been reached. blank line is represented as \n.

memory efficient way is to use loops or use readlines() which stores the result in the list.File I/O Methodswrite(string) method writes the contents of string to the file, returning None.Python strings can have binary data and not just text, but files are required to be opened in binary mode.The write() method does not add a newline character ('\n') to the end of the string.File I/O Methodstell()-returns an integer giving the file objects current position in the file, measured in bytes from the beginning of the file.seek(offset,base)- To change the file objects position, use f.seek(offset, from_what).base = 0= beginning of filebase = 1= current cursor positionbase = 2 = end of file.File I/O other important methodsfile.flush() - Flush the internal buffer, like stdio's fflush.file.isatty() - Returns True if the file is connected to a tty(-like) device, else False.file.next() - Returns the next line from the file each time it is being called.file.truncate([size]) - Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size. file.writelines(sequence)Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.File I/O other important methodsDeductive approach to create a function based on existing function.helps in assigning default values to argument and implement abstraction from user.part of functools() module.partial_func_name=partial(func_name,argname=argvalue);from __future__ import print_function import sys from functools import partial print_stderr = partial(print, file=sys.stderr) print_stderr(Some Error keeps coming on!);

Partial Functionsputting the critical piece of code in try block.performing appropriate actions in except blockseparating non critical logic to improve the performance.nesting of exception handlers happen just like Java.Exception Handlingtry:except []:finally:use else if exception is not being raised. try/except/finallyelse should always come before finally and follow except. it is executed when exception doesnt happen.difference between else and finallythe finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.Debugging Exceptions:helpful attributes: args,errno,strerrorto be used as except IOException as ioe:print(ioe.args);Exception handlingSyntax:raise Exception ([args]);The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).If you need to determine whether an exception was raised but dont intend to handle it, a simpler form of the raise statement allows you to re-raise the exceptionRaising an ExceptionUser Defined Exceptions should typically be derived from the Exception class, either directly or indirectly.class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)We have overriden _init_ to define out custom variable value instead of args.User Defined Exceptions

The simplest form of class definition looks like this: class ClassName: . . .

Class definitions, like function definitions (def statements) must be executed before they have any effect.

When a class definition is entered, a new namespace is created, and used as the local scope thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.Python Object Oriented

Class objects support two kinds of operations: attribute references and instantiation.MyClass.var and MyClass.func are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.var by assignment.Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. for ex- obj=MyClass();Class Objects

The instantiation operation (calling a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:def __init__(self): self.data = []

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

Incorrect to call this the constructor of the class, because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class.

Class instantiationThe first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically. By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, merely a naming convention.Class instantiationThe only operations understood by instance objects are attribute references. There are two kinds of valid attribute names, data attributes and methods.Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to.Instead of using the normal statements to access attributes, you can use following functions:The getattr(obj, name[, default]) : to access the attribute of object.The hasattr(obj,name) : to check if an attribute exists or not.The setattr(obj,name,value) : to set an attribute. If attribute does not exist, then it would be created.The delattr(obj, name) : to delete an attribute.Instance ObjectsEvery Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute:__dict__ : Dictionary containing the class's namespace.__doc__ : Class documentation string or None if undefined. __name__: Class name. __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode. __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.Built-In Class Attributes:

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. You normally won't notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any nonmemory resources used by an instance.Destroying Objects (Garbage Collection):

Syntax:class DerivedClassName(BaseClassName):...The name BaseClassName must be defined in a scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module:class DerivedClassName(modname.BaseClassName):Inheritanceisinstance() :to check an instances type: isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int.issubclass():to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int. However, issubclass(unicode, str) is False since unicode is not a subclass of strInheritanceclass DerivedClassName(Base1, Base2, Base3):A special algorithm has been devised in python to resolve method defination problem in case of multiple inheritance.(check slide footer).It is called as C3 linearization algorithm.based on paper entitled - "A Monotonic Superclass Linearization for Dylan.

Multiple Inheritance

please refer http://python-history.blogspot.in/2010/06/method-resolution-order.html for more details.98Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time.When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate. Syntax it=iter();Iterators

Introduction to Python, Its features, advantages and uses.Python as a language Syntax, structure, standards, formats,rulesPython data structures.Advances Python File Handling, Modules, OOPs concepts, Exception Handling.Python RecapTopics yet to be explored from beginners perspective:Regular ExpressionsHTML ProcessingXML ProcessingScripts and StreamsWeb ServicesMultithreadingNetworkingDatabase AccessCGI ProgrammingGUI ProgrammingInfinite PythonNSIT COE V Sem has 3 batches, COE-I, COE-II, COE-III.Each batch will be sub divided into 3 groups of roughly 18 students. Random18 : PerlRandom18: PythonRandom18: Ruby on RailsA pair of 2 will form a team, who will be working on assigned project.Part 4 Target Audience and ExpectationsEach team will have monthly review on the status of the project assignment.There will be total 4 inspection reviews with Final submission in May.The project in all 3 batches will be compared with each other for comparative grading.

Part 4 Target Audience and ExpectationsThank You