Download presentation
Presentation is loading. Please wait.
Published byDana Barrett Modified over 8 years ago
1
1 Python K. Naik, M. Raju and S. Bhatkar December 3, 2002 CMSC 631
2
2 Outline Introduction Installation and Use Distinct Features Python basics A detail example Comparison with other languages Areas of application References
3
3 Introduction What is Python? InterpretedInterpreted InteractiveInteractive PortablePortable Object-Oriented programming languageObject-Oriented programming language
4
4 Introduction A brief History Invented in 1990 by Guido Van RossumInvented in 1990 by Guido Van Rossum The name PythonThe name Python Intended to be a scripting language on Amoeba OSIntended to be a scripting language on Amoeba OS Python was influenced by ABC and Modula-3Python was influenced by ABC and Modula-3 First public release was in 1991First public release was in 1991
5
5 Introduction Goals Designed to be simple yet powerfulDesigned to be simple yet powerful Allow modular programmingAllow modular programming Great emphasis on readabilityGreat emphasis on readability Rapid application developmentRapid application development Easy to embed in and extend with other languagesEasy to embed in and extend with other languages
6
6 Installation and Use Freely available at http://www.python.org/download http://www.python.org/download Download the appropriate installation for your computer Can be used in both interactive and batch mode IDLE is the editor for writing and running python programs
7
7 Distinct features Extensible (c, c++, fortran, java) Embeddable in applications Object Oriented without being Object- centric Rapid Prototyping Great for readability White space is significant Low maintenance costs Exception handling Free (open source)
8
8 Python Basics In-built data structures Numbers decimal e.g. 631, 3.14decimal e.g. 631, 3.14 octal e.g. O631octal e.g. O631 hexadecimale.g. oxABChexadecimale.g. oxABC complexe.g. 1 + 3jcomplexe.g. 1 + 3j longe.g.122233445656455Llonge.g.122233445656455L Normal Arithmetic and Bit operatorsNormal Arithmetic and Bit operators Integer division truncates e.g. ½ = 0Integer division truncates e.g. ½ = 0
9
9 Python Basics Strings ConcatenationConcatenation “Hello” + “World”-> “HelloWorld” RepetitionRepetition “UMBC” * 3-> “UMBCUMBCUMBC” IndexingIndexing “UMBC”[0]-> “U” SlicingSlicing “UMBC”[1:3]-> “MB” SizeSize len(“UMBC”)-> 4
10
10 Python Basics ComparisonComparison “UMBC” 0 SearchSearch “M” in “UMBC”-> 1 Can also be enclosed in single quotesCan also be enclosed in single quotes e.g. ‘UMBC’
11
11 Python Basic Lists e.g.e.g. aList = [631, “Programming languages”,[331, “programming languages”]] List items need not have the same typeList items need not have the same type Flexible arrays not Lisp-like linked listFlexible arrays not Lisp-like linked list Same operators as for stringsSame operators as for strings More operations append(), insert(), pop(), reverse() and sort()More operations append(), insert(), pop(), reverse() and sort()
12
12 Python Basics Tuples E.g.E.g. aTuple = (631, “Programming Languages”,611, “Computer Architecture”) Nesting is PossibleNesting is Possible Outer Parenthesis is optionalOuter Parenthesis is optional Unlike Lists and like strings tuples are immutableUnlike Lists and like strings tuples are immutable
13
13 Python Basics Dictionaries E.g.E.g. Map = {“Guido”: “Python”, “Ullman”: “ML”} InsertMap[“Ritchie”] = “C”InsertMap[“Ritchie”] = “C” Lookup Map[“Guido”]Lookup Map[“Guido”] Delete del Map[“Ullman”]Delete del Map[“Ullman”] Iterations keys() values() items()Iterations keys() values() items() Presence has_key(“Guido”)Presence has_key(“Guido”) Values could be anythingValues could be anything Keys must be immutableKeys must be immutable
14
14 Python Basics Variables No Need to declareNo Need to declare Not typedNot typed E.g. F = 2 * 4.5 E.g. F = 2 * 4.5 Need to initializeNeed to initialize Everything is a variableEverything is a variable (functions, modules, classes)
15
15 Python Basics References a = b does not make copy of ba = b does not make copy of b b = a, a and b refer to the same objectb = a, a and b refer to the same objectE.g. >>> a = [1,2,3] >>> b = a >>> a.append(4) >>> print b [1, 2, 3, 4]
16
16 Python Basics Flow Control if condition : statementsif condition : statements [elif condition : statement] [else : statement] while condition : statementswhile condition : statements for var in sequence : statementsfor var in sequence : statements breakbreak continuecontinue
17
17 Python Basics An Example (Fibonacci series ) >>> a = 0 >>> b = 1 >>> while b >> while b < 1000 …print b …a, b = b, a + b
18
18 Python Basics Functions and Procedures General FormGeneral Form def(arg1, arg2, …) Statements return# from procedureOR return expression# from function e.g. >>> def fib(n): # write Fibonacci series up to n>>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n."""... """Print a Fibonacci series up to n."""... a, b = 0, 1... a, b = 0, 1... while b < n:... while b < n:... print b,... print b,... a, b = b, a+b... a, b = b, a+b......
19
19 Python Basics Modules A module is a file containing Python definitions and statementsA module is a file containing Python definitions and statements File should have suffix.pyFile should have suffix.py Within a module, the module’s name is available as through global variable _name_.Within a module, the module’s name is available as through global variable _name_. Use “import module-name” to import the functions in this moduleUse “import module-name” to import the functions in this module It is not required to place all import statements at the beginning of a moduleIt is not required to place all import statements at the beginning of a module Some modules are built-in e.g. sysSome modules are built-in e.g. sys
20
20 Python Basics Packages Structure Python’s module namespace using dotted module namesStructure Python’s module namespace using dotted module names E.g. A.B.C refers to the submodule C of module B in package AE.g. A.B.C refers to the submodule C of module B in package A To import module C ->To import module C -> “import A.B.C” and use the fully qualified name OR “from A.B import C” and use only the module name Subpackages need to use fully qualified names to refer to each otherSubpackages need to use fully qualified names to refer to each other
21
21 Python Basics Classes E.g. class ClassName: statements OR statements OR class ClassName(BaseClass1, BaseClass2…) statements Objects x = ClassName() creates a new instance of class ClassName and assigns it to the variable x
22
22 Python Basics An Example class stack: “A well known data structure.” def __init__(self) :#constructor self.items = [] def push(self, x) : self.items.append(x) def pop(self) : x = self.items[-1] del self.items[-1] return x def empty(self) return len(self.items) == 0
23
23 Python Basics Exceptions E.g.try: Print 1/x except ZeroDivisionError, message: print “Can’t divide by zero” print message f = open(file) try:process_file(f) finally : f.close() print “OK”
24
24 Python Basics Raising Exceptions Raise ZeroDivisionExceptionRaise ZeroDivisionException Raise ZeroDivisionException(“can’t divide by zero”)Raise ZeroDivisionException(“can’t divide by zero”) Raise ZeroDivisionException, “can’t divide by zero”Raise ZeroDivisionException, “can’t divide by zero” Python allows user-defined exceptionsPython allows user-defined exceptions
25
25 Example Example def binarySearch(data, item): min = 0; max = len(data) - 1 min = 0; max = len(data) - 1 while 1: while 1: if max < min: if max < min: return -1 return -1 m = (min + max) / 2 m = (min + max) / 2
26
26 Example if data[m] < item: min = m + 1 min = m + 1 elif data[m] > item: max = m - 1 max = m - 1else: return m return m
27
27 Comparisons Vs perl Easier to learnEasier to learn More readableMore readable Fewer side effectsFewer side effects Less Unix biasLess Unix bias Vs Tcl Much fasterMuch faster Less need for C extensionsLess need for C extensions Better java integrationBetter java integration
28
28 Comparison Vs java More concise codeMore concise code Dynamic typingDynamic typing Runs slower but development is fastRuns slower but development is fast No compilationNo compilation Can be integrated with java using JPythonCan be integrated with java using JPython
29
29 Areas of application As a glue language For developing graphical applications For writing Internet protocol applications Database applications Web scripting applications Multimedia applications
30
30 References Python Homepage http://www.python.org/http://www.python.org/http://www.python.org/ Python Tutorial http://www.python.org/tuthttp://www.python.org/tuthttp://www.python.org/tut Python documentation http://www.python.org/dochttp://www.python.org/dochttp://www.python.org/doc
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.