Introduction to python


Published on

Basic knowledge about python

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to python

  1. 1. Introduction to Python Presented by MOHAMMED RAFI.R.M 3rd MCA
  2. 2. CONTENTS
  3. 3. Python in general  What is python? • High level programming language • Emphasize on code readability • Very clear syntax + large and comprehensive standard library • Multiprogramming paradigm: OO, imperative, functional, procedural, reflective • A fully dynamic type system and automatic memory management • Scripting language + standalone executable program + interpreter • Can run on many platform: Windows, Linux, Mactonish
  4. 4. • Updates: • Newest version: 3.2.2 (CPython,JPython, IronPython)
  5. 5. Why Do People Use Python? Because there are many programming languages available today, this is the usual first question of newcomers.  Software quality  Developer productivity  Program portability  Support libraries  Component integration  Enjoyment
  6. 6.  Python execution speed may not always be as fast as that of compiled languages such as C and C++  Whether you will ever care about the execution speed difference depends on what kinds of programs you write.  Processing a file or constructing a graphical user interface (GUI), your program will actually run at C speed, since such tasks are immediately dispatched to compiled C code inside the Python interpreter.
  7. 7. Who Uses Python Today?  Google makes extensive use of Python in its web search systems, and employs Python’s creator.  The YouTube video sharing service is largely written in Python.  The popular BitTorrent peer-to-peer file sharing system is a Python program.  Google’s popular App Engine web development framework uses Python as its application language.  EVE Online, a Massively Multiplayer Online Game (MMOG), makes extensive use of Python.
  8. 8.  Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.  Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.  Industrial Light & Magic, Pixar, and others use Python in the production of animated movies.  JPMorgan Chase, UBS, Getco, and Citadel apply Python for financial market forecasting.
  9. 9. Python’s Capability:  System Programming  GUI  Internet Scripting  Component Integration  Database Programming  Rapid Prototyping  Numeric and Scientific Programming  Gaming, Images, Serial Ports, XML, Robots, and More
  10. 10. Python’s Technical Strengths:  It’s Object-Oriented  It’s Free  It’s Portable  It’s Powerful -Dynamic typing -Automatic memory management -Programming-in-the-large support -Built-in object types
  11. 11. -Built-in tools -Library utilities -Third-party utilities  It’s Mixable  It’s Easy to Use  It’s Easy to Learn
  12. 12.  History of Python Python was conceived in the late1980s and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC programming language capable of exception handling and interfacing with the Amoeba operating system. Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL).
  13. 13. How Python Runs Programs ?
  14. 14.  Windows users fetch and run a self-installing executable file that puts Python on their machines. Simply double-click and say Yes or Next at all prompts.  Linux and Mac OS X users probably already have a usable Python preinstalled on their computers—it’s a standard component on these platforms today.  Some Linux and Mac OS X users (and most Unix users) compile Python from its full source code distribution package.
  15. 15.  The Python Virtual Machine (PVM) - Once your program has been compiled to byte code (or the byte code has been loaded from existing .pyc files), it is shipped off for execution to something generally known as the Python Virtual Machine - The PVM is the runtime engine of Python - It’s always present as part of the Python system, and it’s the component that truly runs your scripts. Technically, it’s just the last step of what is called the “Python interpreter.”
  16. 16.  Python Implementation Alternatives  CPython  Jython  Ironpython
  17. 17. How to run Python?  The Interactive Prompt  simplest way to run Python programs is to type them at Python’s interactive command line sometimes called the interactive prompt. There are a variety of ways to start this command line: in an IDE, from a system console, and so on.  The most platformneutral way to start an interactive interpreter session is usually just to type python at your operating system’s prompt, without any arguments.
  18. 18. • On Windows, you can type python in a DOS console window • On Unix, Linux, and Mac OS X, you might type this command in a shell or terminal window . • Other systems may use similar or platform-specific devices. On handheld devices,for example, you generally click the Python icon in the home or application window to launch an interactive session
  19. 19.  If you have not set your shell’s PATH environment variable to include Python’s install directory, you may need to replace the word “python” with the full path to the Python executable on your machine. On Unix, Linux, and similar, /usr/local/bin/python  or /usr/bin/python will often suffice. On Windows, try typing C:Python30python (for version 3.0)
  20. 20. Lists Dictionaries Tuples Files Numeric Typing Dynamic Typing
  21. 21.  Ordered collections of arbitrary objects  Accessed by offset  Variable-length, heterogeneous, and arbitrarily nestable  Of the category “mutable sequence”  Arrays of object references
  22. 22.  Accessed by key, not offset  Variable-length, heterogeneous, and arbitrarily nestable  Of the category “mutable mapping”  Tables of object references (hash tables)
  23. 23.  Ordered collections of arbitrary objects  Accessed by offset  Of the category “immutable sequence”  Fixed-length, heterogeneous, and arbitrarily nestable  Arrays of object references
  24. 24.  Integers and floating-point numbers  Complex numbers  Fixed-precision decimal numbers  Rational fraction numbers  Sets  Booleans  Unlimited integer precision  A variety of numeric built-ins and modules
  25. 25.  Variables, Objects, References: •Variables are entries in a system table, with spaces for links to objects. •Objects are pieces of allocated memory, with enough space to represent the values for which they stand. •References are automatically followed pointers from variables to objects.
  26. 26. • Notices: It’s also just the default: if you don’t want such behavior, you can request that Python copy objects instead of making references.
  27. 27.  Notices (next): • “is” function returns False if the names point to equivalent but different objects, as is the case when we run two different literal expressions. • Small integers and strings are cached and reused, though, is tells us they reference the same single object.
  28. 28. Statements Assignment, Expression, Print Conditional statements Loop statements Iterations and comprehensions
  29. 29. Python program structures: • Programs are composed of modules. • Modules contain statements. • Statements contain expressions. • Expressions create and process objects.
  30. 30.  Assignment Properties: • Assignments create object references • Names are created when first assigned • Names must be assigned before being referenced • Some operations perform assignments implicitly Assignment Statement Forms:
  31. 31.  Syntax: (underscore or letter) + (any number of letters, digits, or underscores)  Case matters: SPAM is not the same as spam  Reserved words are off-limits
  32. 32.  Call format
  33. 33.  Example:
  34. 34.  General Format: The if/else ternary expression:
  35. 35. Example:
  36. 36. Conditional expression:  Any nonzero number or nonempty object is true.  Zero numbers, empty objects, and the special object None are considered false.  Comparisons and equality tests are applied recursively to data structures.  Comparisons and equality tests return True or False (custom versions of 1 and 0).  Boolean “and” and “or” operators return a true or false operand object
  37. 37. • “and” and “or” operands:
  38. 38.  General while format:
  39. 39.  Notice:
  40. 40.  General Format:
  41. 41.  Loop Coding Techniques: • The built-in range function produces a series of successively higher integers, which can be used as indexes in a for. • The built-in zip function returns a series of parallel-item tuples,which can be used to traverse multiple sequences in a for. • Notice: for loops typically run quicker than while-based counter loops, it’s to your advantage to use tools like these that allow you to use for when possible.
  42. 42.  Iterable: • an object is considered iterable if it is either a physically stored sequence or an object that produces one result at a time in the context of an iteration tool like a for loop. • iterable objects include both physical sequences and virtual sequences computed on demand.  Iterations: • Any object with a __next__ method to advance to a next result,which raises Stop Iteration at the end of the series of results, is considered iterable in Python.
  43. 43. • Example:
  44. 44.  • Example: • (x + 10): arbitrary expression • (for x in L): iterable object • Extend List Comprehension:
  45. 45.  Iterators associated: • built-in type :set, list, dictionary, tuple, file • Dictionary method: keys, values, items • Built-in function: range(multipleiterator), map, zip, filter (single)  • Examples:
  46. 46. Function Basics Scope Arguments Function Advanced Iterations and ComprehensionAdvanced
  47. 47.  Function: A function is a device that groups a set of statements so they can be run more than once in a program.  Why use?: • Maximizing code reuse and minimizing redundancy • Procedural decomposition
  48. 48.  General format:
  49. 49.  Use “def” statements:
  50. 50.  Three different scopes • If a variable is assigned inside a def, it is local to that function. • If a variable is assigned in an enclosing def, it is nonlocal to nested functions. • If a variable is assigned outside all defs, it is global to the entire file.  Notice:  • All names assigned inside a function def statement (or a lambda,an expression we’ll meet later) are locals by default.  • Functions can freely use names as-signed in syntactically enclosing functions and the global scope, but they must declare such nonlocals and globals in order to change them.
  51. 51. • Global Statement:
  52. 52. • Other ways to access Globals
  53. 53.  Factory function • These terms refer to a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory.
  54. 54. • Nested scope and lambda:
  55. 55.  The nonlocal statement: • Is a close cousin to global • Like global: nonlocal declares that a name will be changed in an enclosing scope.  Unlike global: • nonlocal applies to a name in an enclosing function’s scope, not the global module scope outside all defs. • nonlocal names must already exist in the enclosing function’s scope when declared Format:
  56. 56. • Arguments are passed by automatically assigning objects to local variable names. • Assigning to argument names inside a function does not affect the caller. • Changing a mutable object argument in a function may impact the caller. • Immutable arguments are effectively passed “by value.” • Mutable arguments are effectively passed “by pointer.”
  57. 57.  General guidelines: • Coupling: use arguments for inputs and return for outputs. • Coupling: use global variables only when truly necessary. • Coupling: don’t change mutable arguments unless the caller expects it. • Cohesion: each function should have a single, unified purpose. • Size: each function should be relatively small. • Coupling: avoid changing variables in another module file directly
  58. 58.  Examples
  59. 59. • Alternatives
  60. 60.  Lambda format: • Use lambda for: -inline a function definition -defer execution of a piece of code • lambda is an expression, not a statement • lambda’s body is a single expression, not a block of statements. • If you have larger logic to code, use def; lambda is for small pieces of inline code. On the other hand, you may find these techniques useful in moderation
  61. 61. • Examples:
  62. 62.  List Comprehension: • Vs. Map:
  63. 63.  • Vs. filter:
  64. 64.  Generators: • Generator functions: are coded as normal def statements but use yield statements to return results one at a time, suspending and resuming their state between each. • Generator expressions: are similar to the list comprehensions of the prior section, but they return an object that produces results on demand instead of building a result list.
  65. 65.  Generator functions
  66. 66. Class Coding Basics Class Coding Detail Advanced Class topics
  67. 67.  OOP program must show: • Abstraction (or sometimes called encapsulation) • Inheritance (vs. composition) • Polymorphism • Class vs. Instance Object:  Class: Serve as instance factories. Their attributes provide behavior—data and functions—that is inherited by all the instances generated from them.  Instance: Represent the concrete items in a program’s domain.Their attributes record data that varies per specific object
  68. 68.  Each class statement generates a new class object.  Each time a class is called, it generates a new instance object.  Instances are automatically linked to the classes from which they are created.  Classes are linked to their superclasses by listing them in parentheses in a class header line; the left-to-right order there gives the order in the tree.
  69. 69.  Notice: • Python uses multiple inheritance: if there is more than one superclass listed in parentheses in a class statement (like C1’s here), their left-to-right order gives the order in which those superclasses will be searched for attributes.
  70. 70. • Attributes are usually attached to classes by assignments made within class statements, and not nested inside function def statements. • Attributes are usually attached to instances by assignments to a special argument passed to functions inside classes, called self.
  71. 71.  Class Object: • The class statement creates a class object and assigns it a name. • Assignments inside class statements make class attributes. • Class attributes provide object state and behavior.  Instance Object: • Calling a class object like a function makes a new instance object. • Each instance object inherits class attributes and gets its own namespace. • Assignments to attributes of self in methods make per-instance attributes.
  72. 72.  Class statement: • Assigning names inside the class statement makes class attributes, and nested defs make class methods, but other assignments make attributes, too.
  73. 73.  Examples:
  74. 74.  Method call:
  75. 75.  I believe the trial has shown conclusively that it is both possible and desirable to use Python as the principal teaching language:  it is Free (as in both cost and source code).  it is a flexible tool that allows both the teaching of traditional procedural programming and modern OOP; It can be used to teach a large number of transferable skills;  it is a real-world programming language that can be and is used in academia and the commercial world;  it appears to be quicker to learn and, in combination with its many libraries, this offers the possibility of more rapid student development allowing the course to be made more challenging and varied;
  76. 76. and most importantly, its clean syntax offers increased understanding and enjoyment for students;  Python should be used as the first year teaching language. If used it will be possible to teach students more programming and less of the peculiarities of a particular language. Teaching a mid-level language like C in just one day is inadvisable. Too much time must be spent teaching C and not enough time teaching generic skills to students with no programming experience.  In conclusion, Python offers the optimum compromise of teach ability and applicability.
  77. 77.  ‎ ‎  hon/‎  Learning Python (3th Edition) - Ascher, Lutz (O'Reilly, 2008)