Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Scripting Languages Python basics – scope rules – names and values – parameters to functions – importing modules – module documentation – exercise Scope Lookup Rule ● ● ● ● Order of name resolution – local – global – built-in Name declaration (assignment '=') Built-in (Python) interpreter – creates new name for current and lower scope levels Global (module) – shadows names from upper scope Local (function) When leaving current scope (function) all the local names are lost Values (objects) exist as long as they have at least one binding name – automatic memory management file top-level Local (inner functions) Keywords & built-in functions ● Keywords are reserved ● 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] print = 10 print = 10 ^^ SyntaxError: SyntaxError: invalid invalid syntax syntax ● Do not shadow build-in functions – possible, but not recommended ! ● https://docs.python.org/2/library/functions.html max max == 10 10 print print max([1,2,3]) max([1,2,3]) TypeError: TypeError: 'int' 'int' object object is is not not callable callable Example → global/local scope xx == "x-global" "x-global" xx == "x-global" "x-global" def def toplevel(): toplevel(): xx == "x-local" "x-local" print print xx def def toplevel(): toplevel(): print print xx xx == "x-local" "x-local" print print xx print print xx toplevel() toplevel() print print xx print print xx toplevel() toplevel() print print xx x-global x-global x-local x-local x-global x-global ?? Declaration → global – with global it is possible to access (read/modify) names at global (module/file) scope xx == "old" "old" def def func(): func(): global global xx print print xx xx == "new" "new" print print xx print print xx func() func() print print xx old old old old new new new new Data types modifications ● Names and values/objects are separate items ● ● ● Names are bound to values/objects ● ● ● single value/object may have several names (bindings) value/object exists as long as it has at least one binding Numbers, strings, tuples are immutable ● ● ● names are not values/objects (data structures) any name can be bound to any data type objects any assignment creates a new value (object) old value is lost (unless bound by other name) Lists and dictionaries are mutable ● ● adding/removing of items is done in place sorting/reversing can be done in place Names & numbers/strings a aa == 11 1 a bb == aa b 1 a aa == 22 2 b 1 a bb == b+3 b+3 2 b 1 4 Names & lists/dictionaries a b [0] [1] [2] aa == [1,'abc',[2,'xyz']] [1,'abc',[2,'xyz']] 1 bb == a[2] a[2] 'abc' [0] [1] 2 'xyz' a b.append(3) b.append(3) b [0] [1] [2] 2 1 'abc' a[2]=[0] a[2]=[0] [0] a[0]+=1 a[0]+=1 0 [0] [1] [2] 2 'xyz' 3 Names & lists/dictionaries a a aa == [3,'7',2] [3,'7',2] a.sort() a.sort() [0] [1] [2] [0] [1] [2] 3 7 2 a 3 7 2 a [0] [1] [2] [0] [1] [2] aa == [3,'7',2] [3,'7',2] aa == sorted(a) sorted(a) 3 7 2 3 7 2 [0] [1] [2] 2 3 7 Names and scopes – Inner scopes have access to outer scope names – Declaration of name shadows outer name – Scopes apply to names, not to values/objects a def def sqr(): sqr(): bb == a*a a*a return return bb aa bb bb == == == 22 00 sqr() sqr() b 2 b a 4 b 2 4 b 0 a 0 b 2 0 Passing parameters to functions ● Parameters (names) are passed as copies of names ● ● ● for numbers it is similar to "by-value" in C-language for lists it is similar to "by-reference" in C-language An assignment inside function binds name to new value (name becomes local) – in Python function cannot return results by modifying the parameters def def zero(x): zero(x): xx == 00 xx == 100 100 zero(x) zero(x) Getting results from functions ● by return (recommended) – ● functions can return any collection of objects (not just single value) def def square(x) square(x) return return x*x x*x yy == square(5) square(5) by globals (limited use) – modify objects declared as global PLN2USD PLN2USD == 3.85 3.85 def def change_rate(x) change_rate(x) global global PLN2USD PLN2USD PLN2USD*=1+x PLN2USD*=1+x change_rate(0.01) change_rate(0.01) Getting results from functions ● by mutable parameters – lists, dictionaries numbers numbers == [1,2,3] [1,2,3] def def mul_by_2(x): mul_by_2(x): for for index,value index,value in in enumerate(x): enumerate(x): x[index]=2*value x[index]=2*value print print numbers numbers mul_by_2(numbers) mul_by_2(numbers) print print numbers numbers [1, [1, [2, [2, 2, 2, 4, 4, 3] 3] 6] 6] Examples 1 2 3 def def set_zero(x): set_zero(x): xx == 00 def def set_zero(x): set_zero(x): xx == [0] [0] def def set_zero(x): set_zero(x): x[0] x[0] == 00 aa == 100 100 set_zero(a) set_zero(a) print print aa aa == [100] [100] set_zero(a) set_zero(a) print print aa aa == [100] [100] set_zero(a) set_zero(a) print print aa 100 100 [100] [100] [0] [0] Parameters to functions (1) a 100 def def set_zero(x): set_zero(x): xx == 00 aa == 100 100 set_zero(a) set_zero(a) print print aa a copy x 100 a x 100 0 100 100 a 100 x 0 Parameters to functions (2) a [0] 100 def def set_zero(x): set_zero(x): xx == [0] [0] aa == [100] [100] set_zero(a) set_zero(a) print print aa a [0] x 100 a [0] x 0 100 [100] [100] a [0] x 100 [0] [0] 0 Parameters to functions (3) a [0] 100 def def set_zero(x): set_zero(x): x[0] x[0] == 00 aa == [100] [100] set_zero(a) set_zero(a) print print aa a [0] x 100 a x[0] is a[0] [0] 100 [0] [0] a x 0 x [0] 0 Importing modules ● Python code or functions from other files can be imported to the current program – file named 'module.py' will be included: import module ● when imported, all the global names and function are accessible ● ● name of the module creates a namespace names of globals/functions are prefixed with namespace import import math math xx aa == == 2*math.pi 2*math.pi math.sin(x) math.sin(x) Module namespaces Built-in (Python) interpreter Global scope of program import module1 import module2 name1 func1 module1.name1 module1.func1() module2.name1 module2.func1() module1 namespace module2 namespace name1 = ... name1 = ... def func1() def func1() Importing modules ● import can be selective from module import func1, func2 ● import can rename namespace import module as othername ● import can rename functions ● ● from module import func1 as otherfunc1 import can merge namespeces not recommended! ● from module import * from from math math import import ** xx aa == == 2*pi 2*pi sin(x) sin(x) Examining modules ● from Python interpreter: >>> >>> import import math math >>> dir(math) >>> dir(math) ['__doc__', ['__doc__', '__name__', '__name__', '__package__', '__package__', 'acos', 'acos', 'acosh', 'acosh', 'asin', 'asin', 'asinh', 'asinh', 'atan', 'atan', 'atan2', 'atan2', 'atanh', 'atanh', 'ceil', 'ceil', 'copysign', 'copysign', 'cos', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'factorial', 'floor', 'floor', 'fmod', 'fmod', 'frexp', 'frexp', 'fsum', 'fsum', 'gamma', 'gamma', 'hypot', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'modf', 'pi', 'pi', 'pow', 'pow', 'radians', 'radians', 'sin', 'sin', 'sinh', 'sinh', 'sqrt', 'sqrt', 'tan', 'tan', 'tanh', 'trunc'] 'tanh', 'trunc'] >>> >>> print print math.__name__ math.__name__ math math >>> >>> print print math.__doc__ math.__doc__ This module This module is is always always available. available. It It provides provides access access to to the the mathematical functions defined by the C standard. mathematical functions defined by the C standard. >>> >>> help(math.sin) help(math.sin) Help Help on on built-in built-in function function sin sin in in module module math: math: sin(...) sin(...) sin(x) sin(x) Return Return the the sine sine of of xx (measured (measured in in radians). radians). Code merging ● Imported code is merged with current program ● Imported global-scope code is executed test.py """ """ Module Module test""" test""" import import test test def def test1(): test1(): print print "test1" "test1" print print "Hello" "Hello" ## global global scope scope print print "Testing "Testing test1()" test1()" test1() test1() Testing Testing test1() test1() test1 test1 Hello Hello Program structure – The global-scope code should be moved to function ● ● ● it is good practice to use main() function for a global scope code global declarations should be kept minimal functions should exchange data explicitly (by parameters and returns, not by globals) imports imports declarations declarationsof ofglobals globals declarations declarationsof offunctions functions def def main(): main(): declarations declarationsof oflocals locals main mainprogram programbody body main() main() #global #global scope scope Program/module structure – Global-code is executed conditionally: ● ● – when imported, its global-scope code must not be executed when run as main program, its global code should be executed Python programs have built-in attribute __name__, ● if __name__ == "__main__": – ● the code is executed as primary program otherwise (__name__ is the name of the module) – – the code is imported as module no global-scope code should be executed Program/module structure – Global-scope code: ● ● for modules: should contain the demonstration of usage, executed when module is run as primary program for programs: the call to main() program function imports imports declarations declarationsof ofglobals globals declarations declarationsof offunctions functions imports imports declarations declarationsof ofglobals globals declarations declarationsof offunctions functions def def main(): main(): demonstration demonstrationcode code or ormain mainprogram programbody body if if __name__ __name__ == == "__main__": "__main__": demonstration demonstrationcode code or ormain mainprogram programbody body if if __name__ __name__ == == "__main__": "__main__": main() main() Program/module documentation ● Python supports integration of code and docs – Documentation is kept together with the code ● – it is easy do modify and kept up-to-date Documentation can be generated automatically ● with external program "pydoc" → to text, html, … Run "pydoc" from command line: pydoc module → shows text help for a module pydoc -w module → makes html file with documentation pydoc -p 0 → run http server with all available documentation $$ pydoc pydoc -w -w math math $$ pydoc pydoc -p -p 00 pydoc pydoc server server ready ready at at http://localhost:33888/ http://localhost:33888/ Preparing documentation """ """ Global Global module module documentation documentation (single (single line) line) Multi-line Multi-line detailed detailed module description module description May May contain contain empty empty lines. lines. """ """ def def fib_upto(n): fib_upto(n): """ """ Return Return list list containg containg Fibonacci series Fibonacci series up up to to n. n. For For n<=0, n<=0, return return empty empty list. list. """ """ series series == [] [] a, b = 0, a, b = 0, 11 while while aa << n: n: series.append(a) series.append(a) a, a, bb == b, b, a+b a+b return series return series if if __name__ __name__ == == "__main__": "__main__": print fib_upto(100) print fib_upto(100) Exercise → Fibonacci module ● Write Python module fib containing: – – functions: ● fib(n) → returns n-th Fibonacci number using iteration ● fib_r(n) → returns n-th Fibonacci number using recursion ● fib_series(n) → returns list of n-Fibonacci numbers ● fib_upto(n) documentation ● – → returns list of Fibonacci numbers lower than n suitable for automatic generation example of usage ● as conditional global-scope code ● Compare performance of fib() and fib_r() ● Examples: – fib(50) – fib_r(35) → 9227465 (this may take many seconds!) fib_series(10) → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] fib_upto(100) → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] – – → 12586269025