1.08k likes | 1.12k Views
Introduction to Python. Materials based on contents from the course Programming with Python by Chad Haynes. Outline. Overview Built-in objects Functions and scopes Object-oriented programming Functional programming Exercise. Import a library module. Function definition.
E N D
Introduction to Python Materials based on contents from the course Programming with Python by Chad Haynes
Outline • Overview • Built-in objects • Functions and scopes • Object-oriented programming • Functional programming • Exercise
Import a library module Function definition Class definition Comment Object instantiation Calling a function Python At First Glance import math def showArea(shape): print "Area = %d" % shape.area() def widthOfSquare(area): return math.sqrt(area) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height ###### Main Program ###### r = Rectangle(10, 20) showArea(r)
Why use Python? • Simple, clean syntax • Portable • Flexible • Large standard library • Short development time • Lots of 3rd-party tools/add-ons • Many good implementations • CPython, PyPy, IronPython, Jython • Strong support from open-source community
Similarities to Java • Everything inherits from "object" • Also numbers, functions, classes, … • Everything is first-class • Vast, powerful standard library • Garbage collection • Introspection, serialization, threads, net,…
Similarities to C++ • Multi-paradigm • OOP, procedural, generic, functional (a little) • Multiple inheritance • Operator overloading
if (x < 10) { x = x + tmp; y = y * x; } System.out.println(y); Java if x < 10: x = x + tmp y = y * x print y Python Python vs. Java/C++/C • Typing: strong, but dynamic • Names have no type • Objects have types • No declarations • Sparse syntax • No { } for blocks, just indentation • No ( ) for if/while conditions • Interactive interpreter • # for comments
Getting Started • Python already included in most Linux distributions • Windows users can download from: • http://python.org/download • Add python to PATH to run scripts from command line
Hello, World! • C# • Python using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); } } print "Hello, World!"
Variables name x means 23 >>> x = 23 >>> print x 23 >>> x = 'foo' >>> print x foo >>> del x >>> print x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> now it means 'foo' x becomes undefined
Variables • Reference Model • Variables refer to an object • More than one variable can refer to the same object Var1 Var1_copy Var2
Numeric Types • Integers • Generally 32 signed bits • Long Integers • Unlimited size • Format: <number>L • Example: 4294967296L • Float • Platform dependant “double” precision • Complex • Format: <real>+<imag>j • Example: 6+3j
Strings • A sequence of characters enclosed with quotes • 3 quoting styles • 'Single Quotes' • "Double Quotes" • """Triple Quotes""" • Examples >>> print 'This may contain a "' This may contain a " >>> print "A ' is allowed" A ' is allowed >>> print """Either " or ' are OK""" Either " or ' are OK
Built-in Function: raw_input • Syntax: raw_input([prompt]) • Use prompt to ask user to input a string • Example >>> info = raw_input('-> ') -> Here is info >>> print info Here is info
Basic Operations • Arithmetic • + - * // / ** % abs • Example >>> 5 + 3 # Addition • 8 • >>> 2 ** 8 # Exponentiation • 256 • >>> 13 / 4 # Integer (Truncating) Division* • 3 • >>> float(13) / 4 # Float Division • 3.25 • >>> 13 % 4 # Remainder • 1 • >>> abs(-3.5) # Absolute Value • 3.5 * Becomes float division in version 3.x
Basic Operations • Comparison • < <= > >= == != <> • Results in 1 (true) or 0 (false) • Example >>> 4 > 1.5 1 • >>> 'this' != 'that' • 1 • >>> 4+3j == 4-2j • 0 • >>> '5' == 5 • 0 • >>> 0 < 10 < 20 • 1
i1 not i1 1 0 0 1 Basic Operations • Boolean • and or not • Based on Boolean Algebra i1 i2 i1and i2 i1or i2 1 1 1 1 1 0 0 1 0 1 0 1 0 0 0 0
Basic Operations • Boolean • Example >>> 1 == 1 and 2 >= 3 0 • >>> 1 == 1 or 2 >= 3 • 1 • >>> not 5.3 != 2.2 # same as: not (5.3 != 2.2) • 0 • >>> 2 and '23' > '11' or 0 • 1
Strings - Operations • Concatenation (+) • Syntax: string1 + string2 • Example: • >>> 'Rockefeller' + 'University' • 'RockefellerUniversity' • Repetition (*) • Syntax: string * number • Example: • >>> 'dog' * 5 • 'dogdogdogdogdog'
Strings - Formatting • C-Style formatting (extended printf) • Examples: • >>> "%i %s in the basket" % (2, "eggs") • '2 eggs in the basket' • >>> "%f to 2 decimal places: %.2f" %(2.0/9.0, 2.0/9.0) • '0.222222 to 2 decimal places: 0.22' • >>> length = 5 • >>> obj = "fence" • >>> "Length of the %(obj)s is %(length)i" % vars() • 'Length of the fence is 5'
Built-in Function: type • Syntax: type(object) • Used to determine the type of an object • Example • >>> type(2.45) • <type 'float'> • >>> type('x') • <type 'str'> • >>> type(2**34) • <type 'long'> • >>> type(3+2j) • <type 'complex'>
Type Conversions • Use built-in functions to convert between types • str() int() float() long() complex() bool() • Example • >>> str(42.3) • '42.3' • >>> float('-1.32e-3') • -0.00132 • >>> int('0243') • 243 • >>> int(2**34) • Traceback (most recent call last): • File "<pyshell#12>", line 1, in ? • int(2**34) • OverflowError: long int too large to convert to int • >>> long(2**34) • 17179869184L
Data Structures • Lists • Tuples • Dicts
Lists • Construction • Syntax: [elem1, elem2, …] • Heterogeneous, ordered sequence • Mutable • Example: • >>> list1 = [1, 'hello', 4+2j, 123.12] • >>> list1 • [1, 'hello', (4+2j), 123.12] • >>> list1[0] = 'a' • >>> list1 • ['a', 'hello', (4+2j), 123.12]
Lists - Operations • Concatenation (+) • Syntax: list1 + list2 • Example: • >>> [1, 'a', 'b'] + [3, 4, 5] • [1, 'a', 'b', 3, 4, 5] • Repetition (*) • Syntax: list * number • Example: • >>> [23, 'x'] * 4 • [23, 'x', 23, 'x', 23, 'x', 23, 'x']
Indexing • Indexing operator: [ ] • Positive indices count from the left • Negative indices count from the right 0 1 2 3 4 5 6 a b c d e f g -7 -6 -5 -4 -3 -2 -1 sequence[0] == a sequence[-7] == a sequence[6] == g sequence[-1] == g sequence[2] == c sequence[-5] == c
List Slicing • Two indices separated by a colon • Available for both strings and lists • Example • >>> sequence = [0, 1, 2, 3, 4, 5, 6, 7] • >>> sequence[1:4] • [1, 2, 3] • >>> sequence[2:-1] • [2, 3, 4, 5, 6] • Missing Index implies end point • >>> sequence[:2] • [0, 1] • >>> sequence[3:] • [3, 4, 5, 6, 7]
Tuples • Immutable version of list • Syntax: (elem1, elem2, …) • Items in tuple can not be altered • Example: • >>> tuple1 = (1, 5, 10) • >>> tuple1[2] = 2 • Traceback (most recent call last): • File "<pyshell#136>", line 1, in ? • tuple1[2] = 2 • TypeError: object doesn't support item assignment
Built-in Function: len • Syntax: len(object) • Return the length of object • Example • >>> list1 = [1, 2, 3, 4, 5] • >>> len(list1) • 5 • >>> string1 = "length of a string" • >>> len(string1) • 18
'z' 'ab' 2.1 3 Dictionaries • Mapping • Associate a key with a value • Each key must be unique keys 10 [2] (3,8) 'hello' values
Dictionaries • Construction • Syntax: {key1: value1, key2: value2 …} • Unordered map • Example: • >>> dict1 = {'a': 1, 'b': 2} • >>> dict1 • {'a': 1, 'b': 2} • >>> dict1['a'] • 1 • >>> dict1['b'] • 2
Control Flow Examples ifcondition: body elifcondition: body else: body if x%2 == 0: y = y + x else: y = y - x whilecondition: body while i < 0: count = count + 1 fornameiniterable: body for x in [1,2,3]: sum = sum + x
Built-in Function: range • Syntax: range([start,] stop[, step]) • Generate a list of numbers from start to stop stepping every step • start defaults to 0, step defaults to 1 • Example • >>> range(5) • [0, 1, 2, 3, 4] • >>> range(1, 9) • [1, 2, 3, 4, 5, 6, 7, 8] • >>> range(2, 20, 5) • [2, 7, 12, 17]
Controlling Flow • Using range with for • Generate list used by for with range • Example • >>> for i in range(4): • print i • 0 • 1 • 2 • 3
Using Data Structures • Data structures also have methods • Use built-in function dir to list all available methods • Example • >>> lst = [1, 3, 2] • >>> dir(lst) • ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Lists - Methods • append • Syntax: list.append(element) • Add element to end of list • Example: • >>> list1 = [3, '10', 2] • >>> list1.append('new') • >>> list1 • [3, '10', 2, 'new']
Lists - Methods • insert • Syntax: list.insert(index, element) • Insert element into list at position index • Example: • >>> list2 = [0, 1, 2, 3, 4, 5] • >>> list2.insert(3, 'new') • >>> list2 • [0, 1, 2, 'new', 3, 4, 5]
Lists - Methods • sort • Syntax: list.sort([cmpfunc]) • Sort list in place • Example: • >>> list3 = [4, 12, 3, 9] • >>> list3.sort() • >>> list3 • [3, 4, 9, 12]
Getting Help • For interactive use, calling help function will invoke the built-in help system • Call help() without argument for interactive mode >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x :
Defining Functions • Syntax: def func(arg1, …): • body • Body of function must be indented • If no value is returned explicitly, function will return None • Example: • >>> def average(num1, num2, num3): • sum = num1 + num2 + num3 • avg = sum / 3.0 • return avg
Functions • Parameters • Parameters can be any type • A function can take any number of parameters (or none at all) • Example: • >>> def usage(programName, version): • print ‘%s Version %i' % (programName, version) • print 'Usage: %s arg1 arg2‘ % (programName) • >>> usage('Test', 1.0) • Test Version 1.0 • Usage: Test arg1 arg2
Functions • Default Parameters • One or more parameters can be given a default value • The function can be called with fewer arguments than there are parameters • All non-default (required) parameters must precede default parameters • Example: • >>> def printName(last, first, mi=""): • print "%s, %s %s" % (last, first, mi) • >>> printName("Smith", "John") • Smith, John • >>> printName("Smith", "John", "Q") • Smith, John Q
Functions • Calling functions • Syntax: func(arg1, arg2, … argn) • Order of arguments must match order of declared parameters • No type checking is done • Example • >>> def display(arg1, arg2, arg3): • print arg1 • print arg2 • print arg3 • >>> display(1, 'x', 4.3) • 1 • x • 4.3
Functions • Keyword arguments • Functions can be called using the keyword of the argument • Syntax: func(keyword=value, …) • The order of the values passed by keyword does not matter • Example • def keywords(key1="X", key2="X", key3="X",key4="X"): • print key1, key2, key3, key4 • >>> keywords(key3="O", key2="O") • X O O X • >>> keywords() • X X X X
Functions • Functions as variables • Functions can be assigned • Example • def sub(a, b): • return a-b • >>> op = sub • >>> print op(3, 5) • -2 • >>> type(op) • <type 'function'>
Functions • Functions as parameters • Functions can be passed to other functions • Example • def convert(data, convertFunc): • for i in range(len(data)): • data[i] = convertFunc(data[i]) • return data • >>> convert(['1', '5', '10', '53'], int) • [1, 5, 10, 53] • >>> convert(['1', '5', '10', '53'], float) • [1.0, 5.0, 10.0, 53.0] • >>> convert(['1', '5', '10', '53'], complex) • [(1+0j), (5+0j), (10+0j), (53+0j)]
Functions • Returning multiple values • Return a tuple containing the values to return • Example • def separate(text, size=3): • start = text[:size] • end = text[-size:] • return (start, end) • >>> separate('sample text') • ('sam', 'ext') • >>> start, end = separate('sample text') • >>> print start • sam • >>> print end • ext
Generators • Generators are functions that generate sequence of items • Generated sequence can be infinite def fibonacci(): i = j = 1 while True: r, i, j = i, j, i+j yield r for rabbits in fibbonacci(): print rabbits if rabbits > 100: break 1 1 2 3 5 8 13 21 34 55 89 144
Namespaces and Scopes • Namespace • A mapping from names to objects • (Currently) implemented as Python dictionaries • Scope • A region of program where a namespace is directly accessible • Name references search at most 3 scopes: local, global, built-in • Assignments create or change local names by default • Can force arguments to be global with global command