Python / PyS60


Published on

This set of slides gives a short introduction into the world of Python, with a special focus on Python for S60 (PyS60). For smaller projects and prototypes, Python is often the better choice compared to native development in C++, as it's a higher level language that leads to results in a faster and more direct way. Assuming that you already have development experience in Java or C++, these slides jointly introduce basic concepts of Python (variable scope, lists, tuples, classes, ...) as well as their applicance in PyS60.


* The Python programming language
* Modules, variables, lists, tuples, dictionaries, loops
* Basic UI elements: notes, query dialogs, lists
* Functions, arguments, variable scope
* Classes, exception handling
* Application structure, event based development
* String manipulation

Published in: Technology
  • Be the first to comment

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

No notes for slide

Python / PyS60

  1. 1. Symbian OS<br />Python / PyS60<br />1<br />Andreas Jakl, 2009<br />v1.2a – 27 May 2009<br />
  2. 2. PyS60 – Examples<br />ShakerRacer<br />2<br />Andreas Jakl, 2009<br /><br />
  3. 3. PyS60 – Examples <br />PyWuzzler (Benjamin Gmeiner, Yen-Chia Lin)<br />Andreas Jakl, 2009<br />3<br />
  4. 4. PyS60 – Examples<br />NiiMe<br />Andreas Jakl, 2009<br />4<br />Controlling Super Mario<br />by movements (jumping, walking, ...)<br />Playing drums<br />Controlling flight / racinggames with tilting<br /><br />
  5. 5. PyS60 – Examples<br />Andreas Jakl, 2009<br />5<br />Time-lapse Photography<br /> for PyS60<br />PyEDEdit Python source code on the phone<br />pyPoziomicaUse your phone as a level tool<br />
  6. 6. Python<br />What is it all about?<br />Andreas Jakl, 2009<br />6<br />
  7. 7. Python<br />Older than you might think:<br />1989 – 1991 by Guido van Rossum (National Research Institute for Mathematics and Computer Science, Netherlands)<br />Named after Monty Python’s Flying Circus<br />Today:<br />Microcontrollers<br />Mobile Phones<br />Web servers<br />7<br />Andreas Jakl, 2009<br />
  8. 8. Scalable<br />Modular architecture<br />Easy code reuse<br />Huge Python standard library<br />Extension with own C/C++ modules<br />Andreas Jakl, 2009<br />8<br />Shell scripts<br />Huge projects<br />
  9. 9. Mature<br />Andreas Jakl, 2009<br />9<br />
  10. 10. Fast<br />Rapid Application Prototyping<br />Easy to learn – can you read this code?<br />What would this be like in C++ or Java ME? ... <br />Andreas Jakl, 2009<br />10<br />import inbox, audio<br />box = inbox.Inbox()<br />msg_id = box.sms_messages()[0]<br />msg_txt = u&quot;Message: &quot; + box.content(msg_id)<br />audio.say(msg_txt)<br />
  11. 11. Symbian OS + Runtimes<br />Andreas Jakl, 2009<br />11<br />Java ME<br />Python<br />.net<br />Basic<br />Perl<br />Apache / PHP / MySQL<br />Flash Lite<br />Silverlight (soon)<br />Widgets (Web Runtime)<br />Ruby<br />S60(C++)<br />Symbian OS<br />
  12. 12. UI Platforms: S60<br />Unified UI platform based on S60<br />Official UI platform of Symbian Foundation<br />Former name: Series 60<br />Touchscreen support with S60 5th Edition<br />Andreas Jakl, 2009<br />12<br />Nokia N97<br />
  13. 13. UI Platforms: S60<br />Andreas Jakl, 2009<br /><br />Business<br />High-End Multimedia<br />Mass Market<br />Nokia N96<br />Nokia E66<br />Samsung Omnia HD<br />Nokia 6121 Classic<br />Nokia 5800XPressMusic<br />Nokia E71<br />Nokia 5500 Sport<br />Samsung INNOV8<br />Nokia E90<br />13<br />Nokia N85<br />SE Idou<br />Nokia 6210 Navigator<br />
  14. 14. PyS60<br />Python port to S60<br />Allows easy access to:<br />Accelerometer<br />Camera<br />Text-to-speech<br />Location<br />Web services<br />Messaging<br />Bluetooth<br />UI<br />Andreas Jakl, 2009<br />14<br />Web<br />Flash<br />Python<br />Managed code<br />Java<br />Ease of development<br />P.I.P.S.OpenC<br />Symbian C++<br />Native code<br />Functionality and performance<br />
  15. 15. Setup – Phone <br />Install the latest Nokia PC Suite:<br />Download and install PyS60:<br />1.4.x:<br />1.9.x+:<br />Phone:<br />Phone software: PythonForS60_1_x_x_3rdEd.SIS<br />Phone script shell: PythonScriptShell_1_x_x_3rdEd.SIS<br />Andreas Jakl, 2009<br />15<br />PyS60 1.4.x: based on Python 2.3<br />PyS60 1.9.2+: based on Python 2.5.1, supports new sensor framework of S60 3rd Ed., FP2+<br />
  16. 16. Setup – PC <br /><ul><li>Extract SDK plug-in to the S60</li></ul>Andreas Jakl, 2009<br />16<br />
  17. 17. IDEs<br />IDLE – comes with Python SDK<br />C:Program FilesPythonLibidlelibidle.bat<br />PythonWin + Win32 Extensions<br /><br />PyDev Eclipse/Carbide.c++ Plug-in<br /><br />SPE<br /><br />Andreas Jakl, 2009<br />17<br />
  18. 18. Hello World<br />Create a file<br />Connect your phone to the PC (“PC Suite” connection mode)<br />Transfer the script to E:Python (memory card) using the Nokia PC suite file manager<br />Run the script:<br />Andreas Jakl, 2009<br />18<br /><br />print “Hello World”<br />
  19. 19. Hello World – Emulator <br />Copy to:&lt;epocroot&gt;<br />Start the emulator from:&lt;epocroot&gt; eleasewinscwudebepoc.exe<br />Andreas Jakl, 2009<br />19<br />
  20. 20. PyDev + Emulator<br />Either create the project / workspace directly in the python-dir of the emulator<br />Or link the project files to source files in the dir:<br />Andreas Jakl, 2009<br />20<br />
  21. 21. PyS60 – User Interface<br />Starting with the UI<br />Andreas Jakl, 2009<br />21<br />
  22. 22. Module<br />Collection of related functions and data grouped together<br />Has to be imported at the beginning:import appuifw<br />Addressing a function of the module:appuifw.query(label, name)<br />Import multiple modules in a single statement:import appuifw, e32<br />Andreas Jakl, 2009<br />22<br />Python Basics<br />
  23. 23. Query<br />Syntax: appuifw.query(label, type[, initial value])<br />Andreas Jakl, 2009<br />23<br />importappuifw<br />appuifw.query(u&quot;Type a word:&quot;, &quot;text&quot;, u&quot;Hello&quot;)<br />appuifw.query(u&quot;Type a number:&quot;, &quot;number&quot;, 7)<br />appuifw.query(u&quot;Type a date:&quot;, &quot;date&quot;)<br />appuifw.query(u&quot;Type a time:&quot;, &quot;time&quot;)<br />appuifw.query(u&quot;Type a password:&quot;, &quot;code&quot;)<br />appuifw.query(u&quot;Do you like PyS60?&quot;, &quot;query&quot;)<br />number /float<br />text<br />time<br />date<br />code<br />query<br />
  24. 24. Note Dialog<br />Syntax: appuifw.note(text[, type[, global] ] )<br />Andreas Jakl, 2009<br />24<br />importappuifw<br />appuifw.note(u&quot;Hello&quot;)<br />appuifw.note(u&quot;File not found&quot;, &quot;error&quot;)<br />appuifw.note(u&quot;Upload finished&quot;, &quot;conf&quot;)<br />info / default<br />error<br />conf<br />
  25. 25. ImportingOwn Modules<br />Split yourcodeinto multiple files<br />Don‘tcreate a singlehugefile!<br />Additional Python-filescanbeimportedasmodules<br />Add directorycontainingyourmodulestothesystemsearchpathatruntime<br />Andreas Jakl, 2009<br />25<br />import sys<br />__exec_path = &quot;E:ythonamp;quot;<br />sys.path.append(__exec_path)<br /># Import<br />importmyOwnModule<br />
  26. 26. Variables<br />Variables not declared ahead of time<br />Implicit typing<br />Automated memory management<br />Reference counting, garbage collection<br />Variable names can be “recycled”<br />delstatement allows explicit de-allocation<br />Andreas Jakl, 2009<br />26<br />Python Basics<br />
  27. 27. Variables – Example <br />Andreas Jakl, 2009<br />27<br />Python Basics<br />age = 5<br />name = u&quot;Andreas&quot; # u in front of the string: unicode<br />name += age# Doesn&apos;t work, the type isn’t converted automatically<br />name += str(age) # name == Andreas5<br />name = age # name now points to the same object as age; name == 5<br />foo = &quot;xyz&quot;<br />bar = foo# bar points to the same object as foo<br />foo = 123 # a new object is created for foo, bar still points to &quot;xyz“<br />foo<br />“xyz”<br />bar<br />foo<br />“xyz”<br />123<br />bar<br />
  28. 28. Multi-Query Dialog<br />Syntax: appuifw.multi_query(label1, label2)<br />Andreas Jakl, 2009<br />28<br />importappuifw<br />pwd = u&quot;secret&quot;<br />info = appuifw.multi_query(u&quot;Username:&quot;, u&quot;Password:&quot;)<br />if info: // returns a tuple with the info<br />login_id, login_pwd = info<br />iflogin_pwd == pwd:<br />appuifw.note(u&quot;Login successful&quot;, &quot;conf&quot;)<br />else:<br />appuifw.note(u&quot;Wrong password&quot;, &quot;error&quot;)<br />else: // returns None – special type<br />appuifw.note(u&quot;Cancelled&quot;)<br />
  29. 29. if-statement<br />Works like in other languages<br />Blocks are defined by indentation – avoids dangling else<br />ifexpression1:expr1_true_suiteelifexpression2:expr2_true_suiteelse:none_of_the_above_suite<br />Andreas Jakl, 2009<br />29<br />Python Basics<br />
  30. 30. Lists, Tuples and Dictionaries<br />Generic “arrays” for arbitrary number of arbitrary objects<br />Ordered and accessed via index offsets<br />List – created using [ ]<br />Andreas Jakl, 2009<br />30<br />Python Basics<br />myList = [1, 2, 3, 4] # [1, 2, 3, 4]<br />printmyList[0] # 1<br /># Subsets: sequence[starting_index:ending_index]<br />printmyList[1:3] # [2, 3]<br />printmyList[2:] # [3, 4]<br />printmyList[:3] # [1, 2, 3]<br />myList[1] = 5 # [1, 5, 3, 4] <br />myList[2] = [&quot;bla&quot;, (-2.3+4j)] # [1, 5, [&quot;bla&quot;, (-2.3+4j)], 4]<br />printmyList[2][1] # -2.3+4j<br />print 4 inmyList# True<br />
  31. 31. Lists, Tuples and Dictionaries<br />Tuple – created using ( )<br />Immutable – can therefore be used as dictionary keys<br />Also useful when you don’t want a function to be able to change your data<br />Andreas Jakl, 2009<br />31<br />Python Basics<br />myTuple1 = (&apos;python&apos;, &apos;s60&apos;, 27)<br />print myTuple1[0] # python<br />myTuple[1] = &apos;no&apos;# tuples are immutable – exception!<br />myTuple2 = (&apos;symbian&apos;, &apos;uiq&apos;)<br />myTuple3 = myTuple1 + myTuple2<br />print myTuple3 # (&apos;python&apos;, &apos;s60&apos;, 27, &apos;symbian&apos;, &apos;uiq&apos;)<br />
  32. 32. Lists, Tuples and Dictionaries<br />Dictionary – created using { }<br />Mapping type – like associative arrays or hashes in Perl<br />Key-value pairs<br />Keys: almost any Python type, usually numbers or stings<br />Values: arbitrary Python object<br />Andreas Jakl, 2009<br />32<br />Python Basics<br />myDict = {&apos;planet&apos;: &apos;earth&apos;}<br />myDict[&apos;port&apos;] = 80<br />print myDict# {&apos;planet&apos;: &apos;earth&apos;, &apos;port&apos;: 80}<br />print myDict.keys() # [&apos;planet&apos;, &apos;port&apos;]<br />print myDict[&apos;planet&apos;]# earth<br />for key inmyDict:<br />print&quot;key=%s, value=%s&quot; % (key, myDict[key])<br /> # key=planet, value=earth<br /> # key=port, value=80<br />
  33. 33. Popup Menu<br />Syntax: appuifw.popup_menu(list[, label ])<br />Andreas Jakl, 2009<br />33<br />importappuifw<br />items = [u&quot;The Journey&quot;, u&quot;RealReplay&quot;, u&quot;ShakerRacer&quot;]<br />index = appuifw.popup_menu(items, u&quot;Buy:&quot;)<br />if index == 0:<br />appuifw.note(u&quot;Great choice&quot;)<br />elif index == 1:<br />appuifw.note(u&quot;Cool&quot;)<br />elif index == 2:<br />appuifw.note(u&quot;I like that&quot;)<br />elif index == None:<br />appuifw.note(u&quot;Purchase cancelled&quot;)<br />
  34. 34. Selection List<br />Syntax: appuifw.selection_list(choices[, search_field=0])<br />Andreas Jakl, 2009<br />34<br />Search field appears after pressing a letter key<br />importappuifw<br />names = [u&quot;Michael&quot;, u&quot;Devon&quot;, u&quot;Bonnie&quot;, u&quot;April&quot;, u&quot;RC3&quot;]<br />index = appuifw.selection_list(names, 1)<br />if index == 2:<br /> print &quot;I love you!&quot;<br />else:<br /> print &quot;You&apos;re great!&quot;<br />
  35. 35. Multi-Selection List<br />Syntax: appuifw.multi_selection_list(choices[, style=‘checkbox’, search_field=0])<br />Andreas Jakl, 2009<br />35<br />importappuifw<br />names = [u&quot;Michael&quot;, u&quot;Devon&quot;, u&quot;Bonnie&quot;, u&quot;April&quot;, u&quot;RC3&quot;]<br />selections = appuifw.multi_selection_list(names, &apos;checkbox&apos;, 1)<br />print selections<br />Style: checkmarkSelect multiple items with the pen keyNot really important<br />
  36. 36. for loop<br />foriter_variniterable:suite_to_repeat<br />With each loop, iter_var set to current element of iterable<br />Similar to foreachin other languages<br />Andreas Jakl, 2009<br />36<br />Python Basics<br />
  37. 37. for Loop – Examples <br />Andreas Jakl, 2009<br />37<br />Python Basics<br />current letter: T<br />current letter: e<br />current letter: x<br />current letter: t<br /># Iterating over a string<br />foreachLetterin&quot;Text&quot;:<br /> print &quot;current letter:&quot;, eachLetter<br /># Iterating by sequence item<br />nameList = [&quot;Mike&quot;, &quot;Sarah&quot;, &quot;Charles&quot;]<br />foreachNamein sorted(nameList):<br />printeachName<br /># Iterating by sequence index<br />fornameIndexin range(len(nameList)):<br /> print nameList[nameIndex]<br /># Iterate over a range<br />foreachValin range(3):<br />print&quot;value: &quot;, eachVal<br /># Extended syntax:<br /># range(start, end, step = 1)<br />foreachValin range(2, 10, 3):<br />print&quot;value: &quot;, eachVal<br />Charles<br />Mike<br />Sarah<br />Mike<br />Sarah<br />Charles<br />value: 0<br />value: 1<br />value: 2<br />value: 2<br />value: 5<br />value: 8<br />
  38. 38. while loop<br />whileexpression:suite_to_repeat<br />Nice addition: else is executed if loop was not abandoned by break<br />Andreas Jakl, 2009<br />38<br />Python Basics<br />defshowMaxFactor(num):<br /> count = num / 2<br />while count &gt; 1:<br />if num % count == 0:<br />print&quot;Largest factor of %d is %d&quot; % (num, count)<br />break<br /> count -= 1<br />else:<br />print num, &quot;is prime&quot;<br />foreachNumin range(10, 21):<br />showMaxFactor(eachNum)<br />
  39. 39. Example – System Info SMS<br />Andreas Jakl, 2009<br />39<br />importappuifw, messaging, sysinfo<br /># You could use a dictionary as well, but here this is more straightforward later on<br />infoNames = [u&quot;Profile&quot;, u&quot;Battery&quot;, u&quot;Signal DBM&quot;]<br />infoCalls = [&quot;sysinfo.active_profile()&quot;, &quot;sysinfo.battery()&quot;, &quot;sysinfo.signal_dbm()&quot;]<br /># Let the user choose the information he wants to send<br />choices = appuifw.multi_selection_list(infoNames, &quot;checkbox&quot;, 0)<br />infoSms = &quot;&quot;<br />foridxin choices:<br /># Execute the statement(s) stored in the infoCalls-list through the eval-statement, # convert the result to a string and append it to the sms text<br />infoSms += infoNames[idx] + &quot;: &quot; + str(eval(infoCalls[idx])) + &quot;; &quot;<br /># Query the telephone number<br />smsNum = appuifw.query(u&quot;Number:&quot;, &quot;text&quot;, u&quot;+15550135&quot;)<br />ifsmsNum:<br /> # Send the SMS if the user didn’t cancel<br />messaging.sms_send(smsNum, infoSms)<br />appuifw.note(u&quot;Info sent&quot;, &quot;conf&quot;)<br />
  40. 40. Python – Function and Classes<br />Procedural and Object Oriented Development<br />Andreas Jakl, 2009<br />40<br />
  41. 41. Functions – Basics <br />deffunction_name(arguments): [“function_documentation_string”]function_body_suite<br />Supports:<br />Default arguments<br />Variable length arguments<br />Multiple return values<br />Inner functions<br />...<br />Andreas Jakl, 2009<br />41<br />Python Basics<br />deffoo():<br />&quot;foo() -- does&apos;t do anything special.&quot;<br />print&quot;in foo&quot;<br /># Execute the function<br />foo()<br /># Print the help text of the function <br />printfoo.__doc__<br /># foo() -- does&apos;t do anything special.<br />
  42. 42. Functions – Default Arguments<br />Default arguments:deffunc(posargs, defarg1=dval1, defarg2=dval2, ...):<br />Andreas Jakl, 2009<br />42<br />Python Basics<br />defcalcTax(amount, rate=0.0275):<br />return amount + (amount * rate)<br />printcalcTax(100) # 102.75<br />printcalcTax(100, 0.05) # 105.0<br />
  43. 43. Functions – Variable Length Arguments<br />Variable length arguments (unknown number):<br />Non-keyword variable arguments (tuple):deffunc([formal_args,] *vargs_tuple):<br />Argument with * will hold all remaining arguments once all formal parameters have been exhausted<br />Keyword variable arguments (dictionary):deffunc([formal_args,][*vargst,] **vargsd):<br />Andreas Jakl, 2009<br />43<br />Python Basics<br />tupleVarArgs(&apos;abc&apos;)<br /># formal arg 1: abc<br /># formal arg 2: defaultB<br />tupleVarArgs(&apos;abc&apos;, 123, &apos;xyz&apos;, 123.456)<br /># formal arg 1: abc<br /># formal arg 2: 123<br /># another arg: xyz<br /># another arg: 123.456<br />deftupleVarArgs(arg1, arg2=&apos;defaultB&apos;, *theRest):<br />print&quot;formal arg 1: &quot;, arg1<br />print&quot;formal arg 2: &quot;, arg2<br />foreachXtraArgintheRest:<br />print&apos;another arg: &apos;, eachXtraArg<br />
  44. 44. Variable Scope<br />Global scope<br />Declared outside a function<br />Lifespan lasts as long as script is running<br />Local scope<br />Live temporarily as long as function they are defined in is active<br />Searching for identifiers<br />First local, then global<br />Possible to override global variables by creating a local one<br />Andreas Jakl, 2009<br />44<br />Python Basics<br />global_str = &quot;foo&quot;<br />deffoo():<br />local_str = &quot;bar&quot;<br />returnglobal_str + local_str<br />printfoo()<br />local scope<br />
  45. 45. Variable Scope<br />Writing to global variables in functions:<br />Creates a new local variable(pushes global variable out of scope)<br />globalstatement specifically references a named global variable<br />Andreas Jakl, 2009<br />45<br />Python Basics<br />deffoo():<br /> bar = 200<br />print&quot;in foo(), bar is&quot;, bar<br />bar = 100<br />print&quot;in __main__, bar is&quot;, bar<br />foo()<br />print&quot;in __main__, bar still is&quot;, bar<br />deffoo():<br />global bar<br /> bar = 200<br />print&quot;in foo(), bar is&quot;, bar<br />bar = 100<br />print&quot;in __main__, bar is&quot;, bar<br />foo()<br />print&quot;in __main__, bar is now&quot;, bar<br />local scope<br />local scope<br />in __main__, bar is 100<br />in foo(), bar is 200<br />in __main__, bar still is 100<br />in __main__, bar is 100<br />in foo(), bar is 200<br />in __main__, bar is now 200<br />
  46. 46. Classes<br />classMyObject(bases): “Documentation text”class_suite<br />New style classes should be derived from any other class or from object<br />Simplest use: container object for instance attributes<br />Not defined in class definition<br />Only valid for this instance<br />Andreas Jakl, 2009<br />46<br />Python Basics<br />classMyData(object):<br />pass # code is required syntactically, # but no operation is desired<br />mathObj = MyData()<br />mathObj.x = 4<br />mathObj.y = 5<br />printmathObj.x * mathObj.y# 20<br />
  47. 47. Classes – Subclasses, Methods<br />__init__<br />similar to constructor<br />self-parameter<br />Passes reference to current instance<br />Not needed for static or class methods<br />Python wants to be explicitly clear<br />Andreas Jakl, 2009<br />47<br />Python Basics<br />classLibraryEntry(object):<br />def__init__(self, id, title):<br /> = id<br />self.title = title<br />defupdateId(self, newId):<br /> = newId<br />classLibraryBook(LibraryEntry):<br />def__init__(self, id, title, author):<br />LibraryEntry.__init__(self, id, title)<br /> = author<br />defupdateAuthor(self, newAuthor):<br /> = newAuthor<br />libBook = LibraryBook(1, &quot;PyS60&quot;, &quot;Andreas Jakl&quot;)<br />libBook.updateId(2)<br />libBook.updateAuthor(&quot;Nokia&quot;)<br />
  48. 48. Classes – Attributes <br />Instance attributes are set “on-the-fly” by using them<br />Constructor is the first place to set instance attributes<br />Use default arguments for default instance setup<br />Class variables / static data have to be defined<br />Andreas Jakl, 2009<br />48<br />Python Basics<br />Instance attributes<br />Class variables / static data<br />classC(object):<br />foo = 100 # Static data<br />print # 100<br /> = + 1<br />print # 101<br />classLetter(object):<br />def__init__(self, text, author=&quot;Andreas Jakl&quot;, category=“love&quot;):<br />self.text = text<br /> = author<br />self.category = category<br />defprintLetter(self):<br />printself.text,, self.category<br />loveLetter = Letter(&quot;I love you&quot;)<br />print dir(loveLetter) # Print all methods & attributes of this class<br />[&apos;__class__&apos;, &apos;__delattr__&apos;, &apos;__dict__&apos;, &apos;__doc__&apos;, &apos;__getattribute__&apos;, &apos;__hash__&apos;, &apos;__init__&apos;, &apos;__module__&apos;, &apos;__new__&apos;, &apos;__reduce__&apos;, &apos;__reduce_ex__&apos;, &apos;__repr__&apos;, &apos;__setattr__&apos;, &apos;__str__&apos;, &apos;__weakref__&apos;, &apos;author&apos;, &apos;category&apos;, &apos;printLetter&apos;, &apos;text&apos;]<br />
  49. 49. PyS60 – Application Structure<br />How to organize your application<br />Andreas Jakl, 2009<br />49<br />
  50. 50. Application Structure<br />Andreas Jakl, 2009<br />50<br /><br />Navigation pane<br /><br />Dialogappuifw.&lt;dialog_function&gt;- appuifw.query()<br />- appuifw.note()<br />- ...<br /><br /><br />
  51. 51. UI App – Example <br />Andreas Jakl, 2009<br />51<br />importappuifw, e32<br />defquit():<br />print&quot;Exit key pressed&quot;<br />app_lock.signal()<br /> = quit<br /> = u&quot;UI App&quot;<br />print&quot;App is now running&quot;<br />app_lock = e32.Ao_lock()<br />app_lock.wait()<br />print&quot;Application exits&quot;<br />
  52. 52. Callback Function<br />No difference to normal functions<br />Associating function with event: binding<br />Use function name without () to get the function object<br />Compare to function pointers in C<br />Andreas Jakl, 2009<br />52<br />Python Basics<br />defquit():<br />pass# function is empty (instead of {} in C++ / Java)<br /> = quit<br />
  53. 53. Wait for the User<br />Previously: app. exited after executing all lines<br />Event based UI-app: wait for user input<br />Andreas Jakl, 2009<br />53<br />...<br />app_lock = e32.Ao_lock() # Create an instance of an Ao_lock object<br />app_lock.wait()<br />Refer to the Symbian OS course for more information about Active Objects<br />Waiting for events<br />quit() call-back handler<br />app_lock.signal()<br />
  54. 54. Application Body<br />Andreas Jakl, 2009<br />54<br /> = &quot;full&quot;<br /> = “large&quot;<br /> = “normal&quot;<br />
  55. 55. Application Body<br />You can assign several objects to the body<br />Canvas: provides drawable screen area + support for handling raw key events<br />Form: complex forms with various input fields<br />Listbox: shows a list of items (single- or double-line-item)<br />Text: free-form text input<br />Andreas Jakl, 2009<br />55<br />
  56. 56. Application Menu<br />Defined using tuples:<br />Text<br />Call-back function<br />Specify another tuple instead to define a submenu<br />Andreas Jakl, 2009<br />56<br />importappuifw, e32<br />defplay():<br />print&quot;Play file&quot;<br />defvolume_up():<br />print&quot;Volume up&quot;<br />defvolume_down():<br />print&quot;Volume down&quot;<br />defquit():<br />print&quot;Exit key pressed&quot;<br />app_lock.signal()<br /> = quit<br /> = u&quot;mp3 Player&quot;<br /> = [(u&quot;Play&quot;, play), <br /> (u&quot;Volume&quot;, ( (u&quot;Up&quot;, volume_up), (u&quot;Down&quot;, volume_down) ) )]<br />print&quot;App is now running&quot;<br />app_lock = e32.Ao_lock()<br />app_lock.wait()<br />submenu<br />Example based on [1]<br />
  57. 57. String Manipulation<br />Andreas Jakl, 2009<br />57<br />Python Basics<br />txt = &quot;I like Python&quot;<br />print txt[2:6]<br />printtxt.find(&quot;like&quot;)<br />iftxt.find(&quot;love&quot;) == -1:<br />print&quot;What&apos;s wrong with you?&quot;<br />txt.replace(&quot;like&quot;, &quot;love&quot;)<br />printtxt.upper()<br />print&quot;Length&quot;, len(txt)<br />txt2 = &quot;&quot;<br />if txt2:<br />print&quot;txt2 contains characters&quot;<br />else:<br />print&quot;txt2 doesn&apos;t contain characters&quot;<br />url = &quot; &quot;<br />url = url.strip()<br />ifurl.startswith(&quot;http://&quot;):<br />printurl, &quot;is a valid URL&quot;<br />webServiceInput = &quot; 1, 2, 3, 4&quot;<br />printwebServiceInput.replace(&quot; &quot;, &quot;&quot;)<br />txt = &quot;one;two;three&quot;<br />printtxt.split(&quot;;&quot;)<br /> is a valid URL<br />1,2,3,4<br />[&apos;one&apos;, &apos;two&apos;, &apos;three&apos;]<br />like<br />2<br />What&apos;s wrong with you?<br />I LIKE PYTHON<br />Length 13<br />txt2 doesn&apos;t contain characters<br />
  58. 58. String Formatting<br />String slicing like for lists: [start:end]<br />Assemble string based on other variables:<br />Andreas Jakl, 2009<br />58<br />Python Basics<br />print &quot;Host: %s Port: %d&quot; % (&quot;Earth&quot;, 80)<br />print &quot;DD.MM.YYYY = %02d.%02d.%d&quot; % (12, 3, 82)<br />list = [3, 2, 1, &quot;go&quot;] # A list has to be converted to a tuple first<br />print &quot;Counting: %d, %d, %d, %s&quot; % tuple(list)<br />Host: EarthPort: 80<br />DD.MM.YYYY = 12.03.82<br />Counting: 3, 2, 1, go<br />
  59. 59. Example – Inbox Search <br />Andreas Jakl, 2009<br />59<br />import inbox, appuifw<br /># Create an instance of the Inbox object<br />box = inbox.Inbox()<br /># Query search phrase<br />query = appuifw.query(u&quot;Search for:&quot;, &quot;text&quot;).lower()<br />hits = []<br />ids = []<br /># sms_messages() returns message IDs for all messages in the SMS inbox<br />forsms_idinbox.sms_messages():<br /> # Retrieve the full message text and convert it to lowercase<br />msg_text = box.content(sms_id).lower()<br />ifmsg_text.find(query) != -1:<br /> # If the text was found, store a preview<br />hits.append(msg_text[:25])<br />ids.append(sms_id)<br /># Display all results in a list<br />index = appuifw.selection_list(hits, 1)<br />if index &gt;= 0:<br /> # Show the full text of the selected message<br />appuifw.note(box.content(ids[index]))<br />
  60. 60. Event Loop<br />e32.Ao_lock waits for events, but stops execution<br />Game: <br />App. has to be active all the time<br />But still needs respond to events (keys, ...)<br />Andreas Jakl, 2009<br />60<br />Initialize event call-backs<br />while &lt;end condition&gt;:<br /> Update game state<br /> Redraw screen<br /> Pause / yield<br />Sleep (+ execute waiting active objects):<br /> e32.ao_sleep(interval)<br />Yield (just execute ready active objects withhigher priority)<br /> e32.ao_yield()<br />
  61. 61. Exception Handling<br />The Python way of<br />Andreas Jakl, 2009<br />61<br />
  62. 62. Exceptions<br />Example:Exception “NameError” raised by the interpreter:<br />Andreas Jakl, 2009<br />62<br />&gt;&gt;&gt; print foo<br />Traceback (most recent call last):<br /> File “&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br /> print foo<br />NameError: name &apos;foo&apos; is not defined<br />
  63. 63. Exceptions<br />try:try_suite # watch for exceptions hereexcept Exception[, reason]:except_suite # exception-handling code<br />Different objects derived from Exception<br />Exception arguments / reasons:<br />May be passed along<br />Not just a string, but contains more information<br />Andreas Jakl, 2009<br />63<br />
  64. 64. Exceptions – Information <br />Andreas Jakl, 2009<br />64<br />try:<br /> f = file(u&quot;c:ythonest.txt&quot;, &quot;w+&quot;)<br />print &gt;&gt; f, &quot;Welcome to Python&quot;<br /><br />print&quot;File contents:&quot;,<br />f.close()<br />exceptIOError, reason:<br />print reason<br />[Errno 2] No such file or directory: u&apos;c:ythonest.txt&apos;<br />printreason.filename<br />printreason.errno<br />printreason.strerror<br />c:python est.txt<br />2<br />No such file or directory<br />
  65. 65. Multiple Exceptions<br />Catching multiple exceptions:<br />Multipleexcept-statements<br />Multiple exceptions in one exceptstatement<br />Catch the base class Exception(no good coding style – you might be silently dropping errors)<br />Andreas Jakl, 2009<br />65<br />
  66. 66. Code Examples<br />Code snippets for:<br />Camera<br />Text to Speech<br />Sound recording / playing<br />Bluetooth<br />Networking<br />Graphics, UI<br />3D (Open GL ES)<br />Sensor<br />...<br />Andreas Jakl, 2009<br />66<br /><br />Additional modules:<br /><br />
  67. 67. Bonus – Acceleration Sensor (3rd Ed (FP1))<br />Andreas Jakl, 2009<br />67<br />import appuifw,e32,sensor<br />defget_sensor_data(status):<br />&quot;Callback function for regular accelerometer status&quot;<br />print &quot;x: %d, y: %d, z: %d&quot; % (status[&apos;data_1&apos;], status[&apos;data_2&apos;], status[&apos;data_3&apos;])<br />defexit_key_handler():<br /># Disconnect from the sensor and exit<br />acc_sensor.disconnect()<br />app_lock.signal()<br /> = exit_key_handler<br /># Retrieve the acceleration sensor<br />sensor_type = sensor.sensors()[&apos;AccSensor&apos;]<br /># Create an acceleration sensor object<br />acc_sensor = sensor.Sensor(sensor_type[&apos;id&apos;],sensor_type[&apos;category&apos;])<br /># Connect to the sensor<br />acc_sensor.connect(get_sensor_data)<br /># Wait for sensor data and the exit event<br />app_lock = e32.Ao_lock()<br />app_lock.wait()<br />
  68. 68. Bonus – Acceleration Sensor (3rd Ed FP2+)<br />Andreas Jakl, 2009<br />68<br />from sensor import *<br />import e32, time, appuifw<br />classDemoApp():<br />def __init__(self):<br />self.accelerometer = AccelerometerXYZAxisData(data_filter=LowPassFilter())<br />self.accelerometer.set_callback(data_callback=self.my_callback)<br />self.counter = 0<br />defmy_callback(self):<br /># For stream sensor data the callback is hit 35 times per sec (On 5800). # The device cannot handle resource hungry operations like print in the callback function # for such high frequencies. A workaround is to sample the data as demonstrated below.<br />ifself.counter% 5 == 0:<br />print &quot;X:%s, Y:%s, Z:%s&quot; % (self.accelerometer.x,<br />self.accelerometer.y, self.accelerometer.z)<br />self.counter = self.counter + 1<br />def run(self):<br />self.accelerometer.start_listening()<br />defexit_key_handler():<br /># Disconnect from the sensor and exit<br />global d<br />d.accelerometer.stop_listening()<br />print &quot;Exiting Accelorometer&quot;<br />app_lock.signal()<br />if __name__ == &apos;__main__&apos;:<br /> = exit_key_handler<br /> d = DemoApp()<br /><br />app_lock = e32.Ao_lock()<br />app_lock.wait()<br />
  69. 69. Literature – Recommended<br />Andreas Jakl, 2009<br />Mobile Python<br />JürgenScheible, Ville Tuulos<br />Complete overview of Python development for PyS60, many small code samples.Status: Symbian OS 9, PyS60 1.4, 2007<br />Free code samples:<br />Core Python Programming (Second Edition)<br />Wesley J. Chun<br />Python for developers who already know other languages. Comprehensive short overview, in later chapters a detailed overview of the individual components.Status: 2007<br />69<br />
  70. 70. Thanks for your attention<br />That’s it!<br />Andreas Jakl, 2009<br />70<br />