Python         OpenSource Object Oriented scripting language         OpenSource Object Oriented scripting languageNom du f...
Agenda of workshop. Introduction to Python Features of Python Python in Enterprise Who use Python (They speak about Py...
Agenda.     Function     Modules     Data Structure      •      List, Tuple, Dict     Sorting     Object Oriented    ...
Introduction to Python     Python is developed by Guido van Rossum, named the language      after the BBC show "Monty Pyt...
Introduction to Python.     Python is an easy to learn, powerful programming language. It has      efficient high-level d...
Features of Python.     Simple     Flexible.     Easy to Learn     Free and Open Source     High-level Language     ...
Python in Enterprise   Frameworks, Web Development and MNCs.Nom du fichier – à compléter   Management Presentation
Python in Enterprise.     Server, Social Network, shopping sites.     Games & Graphics.Nom du fichier – à compléter   Ma...
What User Says ?    YouTube.com      •     "Python is fast enough for our site and allows us to produce maintainable feat...
What User Says ?     University of Maryland      •      "I have the students learn Python in our undergraduate and gradua...
Rapid application Development using Python    • OpenERP Module    • Web Application using DjangoNom du fichier – à complét...
Starting with Python.     Instalation on Linux      •      If you are using a Linux distribution such as Ubuntu, Fedora, ...
First step to Python.     Using The Interpreter Prompt      •      Start the interpreter on the command line by entering ...
Python Literals & Numbers.   Literal Constants    •      An example of a literal constant is a number like 5, 1.23, 9.25e...
Python Strings.     Strings      •      Single Quotes      •      Double Quotes      •      Triple Quotes      •      Esc...
Control Flow statements      The if statement.        •     The if statement is used to check a condition and if the cond...
Control Flows Cont...      The while Statement        •     The while statement allows you to repeatedly execute a block ...
Python Control Flow...     The break Statement      •      The break statement is used to break out of a loop statement i...
Python Functions     Functions are reusable pieces of programs. They allow you to give a      name to a block of statemen...
Python Function Cont...     Local Variables     Using The global Statement     Default Argument Values     Keyword Arg...
Lambda Function     Python supports the creation of anonymous functions (i.e.      functions that are not bound to a name...
Map & Filter     Map      •      One of the common things we do with list and other sequences is applying             an ...
Modules        You have seen how you can reuse code in your program by defining         functions once. What if you wante...
Making Your Own Modules     Creating your own modules is easy, youve been doing it all along!      This is because every ...
Packages   Packages are just folders of modules with a special __init__.py file    that indicates to Python that this fol...
Python Data Structures       Data structures are basically just that - they are structures which        can hold some dat...
Data Structure cont...   Tuple    •      Tuples are used to hold together multiple objects. Think of them as similar to  ...
Python Data Structure cont...     Dictionary      •      A dictionary is like an address-book where you can find the addr...
Python Data Structure   Set    •      Sets are unordered collections of simple objects. These are used when the          ...
Sorting     There are lots of way to sort the data in python.     Each data structure have its own sorting mechanism.  ...
Sorting cont...   sort() method           mylist = ["b", "C", "A"]           mylist.sort()   Dictonary sorting          ...
Object Oriented Programming with Python     Organizing your program which is to combine data and      functionality and w...
Classes      The simplest class possible is shown in the following example.Nom du fichier – à compléter      Management P...
Object Methods      We have already discussed that classes/objects can have methods       just like functions except that...
The __init__method     There are many method names which have special significance in      Python classes. We will see th...
Class And Object Variables     There are two types of fields - class variables and object variables      which are classi...
Inheritance     One of the major benefits of object oriented programming is reuse      of code and one of the ways this i...
Errors and Exceptions Handling     Exception      •      Exceptions occur when certain exceptional situations occur in yo...
Exception cont...     Errors      •      Consider a simple print function call. What if we misspelt print as Print?Nom du...
Handling Exceptions     We can handle exceptions using the try..except statement.     We put all the statements that mig...
Raising Exceptions     You can raise exceptions using the raise statement by providing the      name of the error/excepti...
Try ..Finally       Suppose you are reading a file in your program. How do you ensure        that the file object is clos...
Input / Output     Up to now we have seen how to take input from user and display it      using input, raw_input and prin...
Input/Output.     Methods of File object.      •      read()      •      read_line()      •      readlines()      •      ...
Input/Output     Pickle      •      when you want to save more complex data types like lists, dictionaries, or           ...
Input/Output     If you have an object x, and a file object f that’s been opened for      writing, the simplest way to pi...
Nom du fichier – à compléter   Management Presentation
Contact Us                               Write email at education@openerp.co.in                                      call ...
Upcoming SlideShare
Loading in...5
×

Python Workshop

989

Published on

Beginning in Python

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
989
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
100
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Python Workshop

  1. 1. Python OpenSource Object Oriented scripting language OpenSource Object Oriented scripting languageNom du fichier – à compléter Management Presentation 1
  2. 2. Agenda of workshop. Introduction to Python Features of Python Python in Enterprise Who use Python (They speak about Python) Rapid application Development using Python with OpenERP andDjango. Installation of Python on Windows and Linux Setup Development Enviroments using Eclipse Step to Python String Number Statements & Control Flow Nom du fichier – à compléter Management Presentation
  3. 3. Agenda. Function Modules Data Structure • List, Tuple, Dict Sorting Object Oriented • Class, Object, Inheritence, Polymorphism Errors and Exceptions Handling Input / Output Python QuizNom du fichier – à compléter Management Presentation
  4. 4. Introduction to Python Python is developed by Guido van Rossum, named the language after the BBC show "Monty Pythons Flying Circus".Nom du fichier – à compléter Management Presentation
  5. 5. Introduction to Python. Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Pythons elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.Nom du fichier – à compléter Management Presentation
  6. 6. Features of Python. Simple Flexible. Easy to Learn Free and Open Source High-level Language Platform Independent. Dynamic Type. Extensive Libraries. Object Oriented. Interpreted. Scalable.Nom du fichier – à compléter Management Presentation
  7. 7. Python in Enterprise Frameworks, Web Development and MNCs.Nom du fichier – à compléter Management Presentation
  8. 8. Python in Enterprise. Server, Social Network, shopping sites. Games & Graphics.Nom du fichier – à compléter Management Presentation
  9. 9. What User Says ? YouTube.com • "Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," said Cuong Do, Software Architect, YouTube.com. Google • "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and were looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc. Industrial Light & Magic • "Python plays a key role in our production pipeline. Without it a project the size of Star Wars: Episode II would have been very difficult to pull off. From crowd rendering to batch processing to compositing, Python binds all things together," said Tommy Burnette, Senior Technical Director, Industrial Light & Magic.Nom du fichier – à compléter Management Presentation
  10. 10. What User Says ? University of Maryland • "I have the students learn Python in our undergraduate and graduate Semantic Web courses. Why? Because basically theres nothing else with the flexibility and as many web libraries," said Prof. James A. Hendler.Nom du fichier – à compléter Management Presentation
  11. 11. Rapid application Development using Python • OpenERP Module • Web Application using DjangoNom du fichier – à compléter Management Presentation
  12. 12. Starting with Python. Instalation on Linux • If you are using a Linux distribution such as Ubuntu, Fedora, OpenSUSE it is most likely you already have Python installed on your system. • To test if you have Python already installed on your Linux box, open a shell program (like console or gnome-terminal) and enter the command python -V as shown below. Instalation on Windows • download the latest python version from the website and install it on your system. • Set the environment variable path. Setup Development Enviroments using Eclipse. • http://www.easyeclipse.org/site/distributions/python.htmlNom du fichier – à compléter Management Presentation
  13. 13. First step to Python. Using The Interpreter Prompt • Start the interpreter on the command line by entering python at the shell prompt. • For Windows users, you can run the interpreter in the command line if you have set the PATH variable appropriately. • Ex. print(Hello World) Using Source file. IndentationNom du fichier – à compléter Management Presentation
  14. 14. Python Literals & Numbers. Literal Constants • An example of a literal constant is a number like 5, 1.23, 9.25e-3 or a string like This is a string or "Its a string!". It is called a literal because it is literal - you use its value literally. Numbers • Numbers in Python are of three types - integers, floating point and complex numbers. • Ex. 3.23 and 52.3E-4Nom du fichier – à compléter Management Presentation
  15. 15. Python Strings. Strings • Single Quotes • Double Quotes • Triple Quotes • Escape Sequences Raw Strings Strings Are Immutable String Literal ConcatenationNom du fichier – à compléter Management Presentation
  16. 16. Control Flow statements  The if statement. • The if statement is used to check a condition and if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional. • ExampleNom du fichier – à compléter Management Presentation
  17. 17. Control Flows Cont...  The while Statement • The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause. • Example  The for loop • The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence, sequence is just an ordered collection of items. • The for loop also have optional else statement. • ExampleNom du fichier – à compléter Management Presentation
  18. 18. Python Control Flow... The break Statement • The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has been completely iterated over. • Example The continue Statement • The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop. • ExampleNom du fichier – à compléter Management Presentation
  19. 19. Python Functions Functions are reusable pieces of programs. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. Functions are defined using the def keyword. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. ExampleNom du fichier – à compléter Management Presentation
  20. 20. Python Function Cont... Local Variables Using The global Statement Default Argument Values Keyword Arguments Variable Arguments. The return Statement Return Multiple value DocStrings • Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand.Nom du fichier – à compléter Management Presentation
  21. 21. Lambda Function Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". Example l=[1,2,3,4,5,6,7,8,9,10] print map(lambda x: x*5,l) • Example Foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print filter(lambda x: x % 3 == 0, foo) • We can also pass lambda functions as function parameters without assigning to to intermediate variables.Nom du fichier – à compléter Management Presentation
  22. 22. Map & Filter Map • One of the common things we do with list and other sequences is applying an operation to each item and collect the result. Items = [1, 2, 3, 4, 5] def sqr(x): return x ** 2 list(map(sqr, items)) Filter • As the name suggests filter extracts each element in the sequence for which the function returns True. list( filter((lambda x: x < 0), range(-5,5)))Nom du fichier – à compléter Management Presentation
  23. 23. Modules  You have seen how you can reuse code in your program by defining functions once. What if you wanted to reuse a number of functions in other programs that you write?  The answer is modules.  There are various methods of writing modules, but the simplest way is to create a file with a .py extension that contains functions and variables.  A module can be imported by another program to make use of its functionality.Nom du fichier – à compléter Management Presentation
  24. 24. Making Your Own Modules Creating your own modules is easy, youve been doing it all along! This is because every Python program is also a module. You just have to make sure it has a .py extension. Example of ModuleNom du fichier – à compléter Management Presentation
  25. 25. Packages Packages are just folders of modules with a special __init__.py file that indicates to Python that this folder is special because it contains Python modules.Nom du fichier – à compléter Management Presentation
  26. 26. Python Data Structures  Data structures are basically just that - they are structures which can hold some data together. In other words, they are used to store a collection of related data.  List • A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. • The list of items should be enclosed in square brackets so that Python understands that you are specifying a list. Once you have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say that a list is a mutable data type i.e. this type can be altered. • Example o [1,2,3, a]Nom du fichier – à compléter Management Presentation
  27. 27. Data Structure cont... Tuple • Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive functionality that the list class gives you. One major feature of tuples is that they are immutable like strings i.e. you cannot modify tuples. • Tuples are defined by specifying items separated by commas within an optional pair of parentheses. • Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values i.e. the tuple of values used will not change. • Example o (1,2,3)Nom du fichier – à compléter Management Presentation
  28. 28. Python Data Structure cont... Dictionary • A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values (details). • Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name. • Example o {a: 1, b:2}Nom du fichier – à compléter Management Presentation
  29. 29. Python Data Structure Set • Sets are unordered collections of simple objects. These are used when the existence of an object in a collection is more important than the order or how many times it occurs. • Example o bri = set([brazil, russia, india])Nom du fichier – à compléter Management Presentation
  30. 30. Sorting There are lots of way to sort the data in python. Each data structure have its own sorting mechanism. List Sort numlist=[1, 2.1, 2, 1.1, 1.3, 1.8, 1.9, 2.4, 2.8, 2.5, 2.8, 2.4, 2.1, 2.3, 1.1, 1.3, 1.3, 1.2, 1.2, 3, 3.1, 2.5, 3.5] numlist.sort() print (numlist) • Custom Sorting With key= strs = [ccc, aaaa, d, bb] print sorted(strs, key=len) print sorted(strs, key=str.lower)Nom du fichier – à compléter Management Presentation
  31. 31. Sorting cont... sort() method mylist = ["b", "C", "A"] mylist.sort() Dictonary sorting import operator x = {1: 2, 3: 4, 4:3, 2:1, 0:0} sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))Nom du fichier – à compléter Management Presentation
  32. 32. Object Oriented Programming with Python Organizing your program which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm. Classes and objects are the two main aspects of object oriented programming. Class contains data and methods. The self • Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.Nom du fichier – à compléter Management Presentation
  33. 33. Classes  The simplest class possible is shown in the following example.Nom du fichier – à compléter Management Presentation
  34. 34. Object Methods  We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable.  ExampleNom du fichier – à compléter Management Presentation
  35. 35. The __init__method There are many method names which have special significance in Python classes. We will see the significance of the __init__ method now. The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. ExampleNom du fichier – à compléter Management Presentation
  36. 36. Class And Object Variables There are two types of fields - class variables and object variables which are classified depending on whether the class or the object owns the variables respectively. Class variables are shared - they can be accessed by all instances of that class. There is only one copy of the class variable and when any one object makes a change to a class variable, that change will be seen by all the other instances. Object variables are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in anyway to the field by the same name in a different instance. ExampleNom du fichier – à compléter Management Presentation
  37. 37. Inheritance One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the inheritance mechanism. Inheritance can be best imagined as implementing a type and subtype relationship between classes. Simple inheritance. Multiple inheritance. Multi level Inheritance.Nom du fichier – à compléter Management Presentation
  38. 38. Errors and Exceptions Handling Exception • Exceptions occur when certain exceptional situations occur in your program. For example, what if you are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program was running? Such situations are handled using exceptions. • We will try to read input from the user. Press ctrl-d and see what happens.Nom du fichier – à compléter Management Presentation
  39. 39. Exception cont... Errors • Consider a simple print function call. What if we misspelt print as Print?Nom du fichier – à compléter Management Presentation
  40. 40. Handling Exceptions We can handle exceptions using the try..except statement. We put all the statements that might raise exceptions/errors inside the try block and then put handlers for the appropriate errors/exceptions in the except clause/block. The except clause can handle a single specified error or exception, or a parenthesized list of errors/exceptions. If no names of errors or exceptions are supplied, it will handle all errors and exceptions. If any error or wxception is not handeled then default python handler will called. You can also have an else clause associated with a try..except block. The else clause is executed if no exception occurs.Nom du fichier – à compléter Management Presentation
  41. 41. Raising Exceptions You can raise exceptions using the raise statement by providing the name of the error/exception and the exception object that is to be thrown. The error or exception that you can arise should be class which directly or indirectly must be a derived class of the Exception class. ExampleNom du fichier – à compléter Management Presentation
  42. 42. Try ..Finally  Suppose you are reading a file in your program. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the finally block.  ExampleNom du fichier – à compléter Management Presentation
  43. 43. Input / Output Up to now we have seen how to take input from user and display it using input, raw_input and print statements. Another common type of input/output is dealing with files. The ability to create, read and write files is essential to many programs. Files • You can open and use files for reading or writing by creating an object of the file class and using its read, readline or write methods appropriately to read from or write to the file. • The ability to read or write to the file depends on the mode you have specified for the file opening. • Then finally, when you are finished with the file, you call the close method to tell Python that we are done using the file.Nom du fichier – à compléter Management Presentation
  44. 44. Input/Output. Methods of File object. • read() • read_line() • readlines() • write(stringToWrite) • seek(seekingByte) • close()Nom du fichier – à compléter Management Presentation
  45. 45. Input/Output Pickle • when you want to save more complex data types like lists, dictionaries, or class instances, things get a lot more complicated. • Python provides a standard module called pickle. • This is an amazing module that can take almost any Python object and convert it to a string representation; this process is called pickling. • Reconstructing the object from the string representation is called unpickling.Nom du fichier – à compléter Management Presentation
  46. 46. Input/Output If you have an object x, and a file object f that’s been opened for writing, the simplest way to pickle the object takes only one line of code: • pickle.dump(x, f) To unpickle the object again, if f is a file object which has been opened for reading: • x = pickle.load(f)Nom du fichier – à compléter Management Presentation
  47. 47. Nom du fichier – à compléter Management Presentation
  48. 48. Contact Us Write email at education@openerp.co.in call us on 91 79 400 500 48Nom du fichier – à compléter Management Presentation
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×