Sei sulla pagina 1di 83

Developer Training

Python
Workbook

BO-EN-Python-20080613.pdf

Python

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

2
BO-EN-Python-20080613.pdf

[NOKIA OFFICAL COURSEWARE]


IMPORTANT: READ CAREFULLY BEFORE INSTALLING, DOWNLOADING, OR USING THE NOKIA OFFICIAL COURSEWARE

NOKIA END-USER AGREEMENT


This Nokia End-User Agreement (this Agreement) is between You the end user (either an individual or an entity), and Nokia Corp. (Nokia), the licensor. This Agreement authorizes You to use the Nokia Official Courseware specified in Section 1 below, which may be stored on a CD-ROM, sent to You by electronic mail or in written hardcopy, or downloaded from Nokias Web pages or Servers or from other sources under the terms and conditions set forth below. If You download the Software from a CD-ROM, then the legal notices and any other terms stated therein (collectively, the CD-ROM Terms) shall be incorporated into and made a part of this Agreement by this reference and also govern your downloading and usage of the Nokia Official Courseware. This is an agreement providing certain limited end-user rights and not an agreement for sale. Nokia continues to own the copy of the Nokia Official Courseware You receive and the physical media contained in any package and any other copy that You are authorized to make pursuant to this Agreement. Read this Agreement carefully before installing, downloading, or using the Nokia Official Courseware. By breaking the seal of the Nokia Official Courseware packet or clicking on the I Accept button while installing, downloading, and/or using the Software, You agree to the terms and conditions of this Agreement. If You do not agree to all of the terms and conditions of this Agreement, promptly click the Decline or I Do Not Accept button, cancel the installation or downloading, or destroy or return the Nokia Official Courseware and accompanying documentation to Nokia. YOU AGREE THAT YOUR USE OF THE NOKIA OFFICIAL COURSEWARE CONSTITUTES YOUR ACKNOWLEDGEMENT THAT YOU HAVE READ THIS AGREEMENT, UNDERSTAND IT, AND AGREE TO BE BOUND BY ITS TERMS AND CONDITIONS. 1. NOKIA OFFICIAL COURSEWARE. As used in this Agreement, the term Nokia Official Courseware means, collectively: (i) any software identified in this Agreement, (ii) all contents of the disk(s), CD-ROM(s), electronic mail and its file attachments, or other media with which this Agreement is provided, including the object code form of the software delivered via a CD-ROM, electronic mail, or Web page, (iii) digital images, video presentations, stock photographs, clip art, or othe artistic works (Stock Files), (iv) related explanatory written materials and any other possible documentation related thereto (Documentation), (v) fonts, (vi) upgrades, modified versions, updates, additions, and copies of the Nokia Official Courseware (collectively Updates), if any, and (vii) any printed or written materials provided and licensed to You by Nokia under this Agreement. 2. END-USER RIGHTS AND USE. Nokia grants to You a non-exclusive, royalty-free, non-transferable right to use and install the Nokia Official Courseware on the local hard disk(s) or other permanent storage media of one computer and use the Nokia Official Courseware on a single computer or terminal at a time. 3. LIMITATIONS ON END-USER RIGHTS. You may not copy, distribute, or make derivative works of the Nokia Official Courseware, except as follows: (a) You may make one copy of the Nokia Official Courseware on magnetic media as an archival backup copy, provided Your archival backup copy is not installed or used on any computer. Any other copies You make of the Nokia Official Courseware are in violation of this Agreement. (b) You may not use, modify, translate, reproduce, or transfer the right to use the Nokia Official Courseware or copy the Nokia Official Courseware except as expressly provided in this Agreement. (c) You may not distribute, sale, resell, sublicense, rent, lease, or lend the Nokia Official Courseware or any part thereof. (d) You may not reverse engineer, reverse compile, disassemble, or otherwise attempt to discover the source code of any software included in the Nokia Official Courseware (except to the extent that this restriction is expressly prohibited by law) or create derivative works based on the Nokia Official Courseware. (e) Unless stated otherwise in the Documentation, You shall not display, modify, reproduce, or distribute any of the Stock Files included with the Nokia Official Courseware. In the event that the Documentation allows You to display the Stock Files, You shall not distribute the Stock Files on a stand-alone basis, i.e., in circumstances in which the Stock Files constitute the primary value of the product being distributed. You should review the Readme files associated with the Stock Files that You use to ascertain what rights You have with respect to such mate Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

3
BO-EN-Python-20080613.pdf

Python

rials. Stock Files may not be used in the production of libelous, defamatory, fraudulent, infringing, lewd, obscene, or pornographic material or in any otherwise illegal manner. You may not register or claim any rights in the Stock Files or derivative works thereof. (f) You may not use the Nokia Official Courseware to provide training in any class that is not a certified Nokia Course. (g) You agree that You shall only use the Nokia Official Courseware in a manner that complies with all applicable laws in the jurisdiction in which You use the Nokia Official Courseware, including, but not limited to, applicable restrictions concerning copyright and other intellectual property rights. 4. COPYRIGHT. The Nokia Official Courseware and all rights, without limitation including proprietary rights therein, are owned by Nokia and/or its licensors and affiliates and are protected by international treaty provisions and all other applicable national laws of the country in which it is being used. The structure, organization, and code of the Nokia Official Courseware are the valuable trade secrets and confidential information of Nokia and/or its licensors and affiliates. You must not copy the Nokia Official Courseware, except as set forth in Section 3 above. Any copies that You are permitted to make pursuant to this Agreement must contain the same copyright and other proprietary notices that appear on the Nokia Official Courseware. 5. MULTIPLE ENVIRONMENT SOFTWARE / MULTIPLE LANGUAGE SOFTWARE / DUAL MEDIA SOFTWARE / MULTIPLE COPIES / UPDATES. If the Nokia Official Courseware supports multiple platforms or languages, or if You receive the Nokia Official Courseware on multiple media, or if You otherwise receive multiple copies of the Nokia Official Courseware, the number of computers on which all versions of the Nokia Official Courseware are installed shall be one computer. You may not rent, lease, sublicense, lend, or transfer versions or copies of the Nokia Official Courseware that You do not use. If the Nokia Official Courseware is an Update to a previous version of the Nokia Official Courseware, You must possess valid end-user rights to such a previous version in order to use the Update, and You may use the previous version for ninety (90) days after You receive the Update in order to assist You in the transition to the Update. After such time, You no longer have a right to use the previous version, except for the sole purpose of enabling You to install the Update. 6. THIRD-PARTY LINKS. THE NOKIA OFFICIAL COURSEWARE MAY INCLUDE LINKS TO THIRD PARTY SITES. SUCH LINKED SITES, IF ANY, ARE NOT UNDER THE CONTROL OF NOKIA AND NOKIA IS NOT RESPONSIBLE FOR THEIR CONTENTS, OR ANY OTHER LINK CONTAINED THEREIN. NOKIA PROVIDES THESE LINKS ONLY AS A CONVENIENCE, AND THE INCLUSION OF ANY SUCH LINK DOES NOT IMPLY ENDORSEMENT BY NOKIA OF THE LINKED SITE. 7. COMMENCEMENT & TERMINATION. This Agreement is effective from the first date that You install the Nokia Official Courseware. You may terminate this Agreement at any time by permanently deleting, destroying, and returning, at Your own costs, the Nokia Official Courseware, all backup copies, and all related materials provided by Nokia. Your end-user rights automatically and immediately terminate without notice from Nokia if You fail to comply with any provision of this Agreement. In such an event, You must immediately delete, destroy, or return at Your own cost, the Nokia Official Courseware, all backup copies, and all related material to Nokia. 8. NO WARRANTY. YOU ACKNOWLEDGE THAT THE NOKIA OFFICIAL COURSEWARE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, AND TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, NEITHER NOKIA, ITS LICENSORS OR AFFILIATES, NOR THE COPYRIGHT HOLDERS MAKE AN REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR THAT THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER RIGHTS. THE NOKIA OFFICIAL COURSEWARE, ANY DOCUMENTATION AND OTHER INFORMATION, MAY INCLUDE TECHNI- CAL INACCURACIES OR TYPOGRAPHICAL ERRORS. THERE IS NO WARRANTY BY NOKIA OR BY ANY OTHER PARTY THAT THE OPERATION OF ANY SOFTWARE INCLUDED WITH THE NOKIA OFFICIAL COURSEWARE WILL BE UNINTERRUPTED OR ERROR-FREE. 9. NO OTHER OBLIGATIONS. This Agreement creates no obligations on the part of Nokia other than as specifically set forth herein. 10. LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL NOKIA, ITS EMPLOYEES OR LICENSORS OR AFFILIATES BE LIABLE FOR ANY LOST PROFITS, REVENUE, SALES, DATA, OR COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, PROPERTY DAMAGE, PERSONAL INJURY, INTERRUPTION OF BUSINESS, LOSS OF BUSINESS INFORMATION, OR FOR ANY SPECIAL, DIRECT, INDIRECT, INCIDENTAL, ECONOMIC, COVER, PUNITIVE, SPECIAL, OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED AND WHETHER ARISING UNDER CONTRACT, TORT, NEGLIGENCE, OR OTHER THEORY OF LIABILITY ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF NOKIA OR ITS LICENSORS OR AFFILIATES ARE ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME COUNTRIES/STATES/JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF LIABILITY, BUT MAY ALLOW LIABILITY TO BE LIMITED, IN SUCH CASES, NOKIA, ITS EMPLOYEES OR LICENSORS OR AFFILIATES' LIABILITY SHALL BE LIMITED TO U.S. $50. Nothing contained in this Agreement shall prejudice the statutory rights of any party dealing as a consumer. Nothing contained in this Agreement limits Nokia's liability to You in the event of death or per Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

4
BO-EN-Python-20080613.pdf

sonal injury resulting from Nokia's negligence. Nokia is acting on behalf of its employees and licensors or affiliates for the purpose of disclaiming, excluding, and/or restricting obligations, warranties, and liability as provided in this Section 9, but in no other respects and for no other purpose. 11. TECHNICAL SUPPORT. Nokia has no obligation to furnish You with technical support unless separately agreed to in writing between You and Nokia. 12. EXPORT CONTROL. The Nokia Official Courseware and any related technical data are subject to the U.S. Export Administration Regulations and may be subject to export and import laws, regulations and restrictions in other countries. You agree to comply strictly with all such laws, regulations and restrictions, and acknowledge that You have the responsibility to obtain any licenses or permits that may be required to import, use, export, re-export, or otherwise transfer or disclose of the Nokia Official Courseware or any related technical data. You further agree that except as authorized, You shall not export, re-export or otherwise transfer or disclose of the Nokia Official Courseware, the related technical data or any direct product thereof; (i) into any country embargoed by U.S. export regulations; (ii) to entities controlled by such countries or to nationals of such countries; or (iii) to anyone on the U.S. Treasury Department's list of Specially Designated Nationals and Blocked Persons, the U.S. Commerce Department's Denied Persons List, or the U.S. Commerce Department's Entity List. 13. NOTICES. All notices and return of the Nokia Official Courseware and Documentation should be delivered to: NOKIA CORPORATION Forum Nokia Developer Training Keilalahdentie 4 FIN-02150 Espoo Finland Attn: Tero Putkonen 14. GOVERNING LAW, ARBITRATION & GENERAL PROVISIONS. This Agreement shall be governed by and construed in accordance with the laws of Finland without regard to its conflicts of laws rules. Any disputes relating to or arising in connection with this Agreement shall be finally settled in arbitration. The arbitrator is to be appointed by the Arbitration Committee of the Central Chamber of Commerce of Finland and the rules of the said Committee are to be followed in the arbitration. The award shall be final and binding and enforceable in any court of competent jurisdiction. The arbitration shall be held in Helsinki, Finland, in English language. The parties undertake and agree that all arbitral proceedings conducted with reference to this Agreement shall be kept strictly confidential and all information disclosed in the course of such arbitral proceeding shall be used solely for the purpose of those proceedings. Notwithstanding the foregoing, nothing in this Agreement shall be deemed to limit the Parties' rights to seek interim injunctive relief or to enforce an arbitration award in any court of law. If any part of this Agreement is found void and unenforceable, it will not affect the validity of the balance of the Agreement, which shall remain valid and enforceable according to its terms. This Agreement may be modified only in writing by an authorized officer of Nokia. This is the entire agreement between Nokia and You relating to the Nokia Official Courseware, and it supersedes any prior representations, discussions, undertakings, end-user agreements, communications, or advertising relating to the Nokia Official Courseware. PLEASE SUBMIT ANY ACCOMPANYING REGISTRATION FORMS TO RECEIVE REGISTRATION BENEFITS WHERE APPLICABLE. *** End ***

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

5
BO-EN-Python-20080613.pdf

Python

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

6
BO-EN-Python-20080613.pdf

About This Course


Course Description
This course introduces object-oriented programming language Python.

Audience
The readers of this document are Python developers who want to use Python in the S60 platform. This is not a generic Python course, so, for example, Python use in unit testing is not covered.

Student Prerequisites
Before attending this course, students must have: Object-oriented programming experience with some programming language (C++, Java); Helpful: generic Symbian and S60 knowledge.

Course Objectives
At the end of the course, students will be able to do the following: Write Python programs; Deploy and test programs; Use Python S60 APIs.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

7
BO-EN-Python-20080613.pdf

Python

Document Conventions
The following conventions are used in course materials to distinguish elements of the text.

Convention Courier10 BT | [ ] ... { } // // // /* ... */ <!-- ... -->

Use
Represents code samples or examples of screen text. Separates an either/or choice in syntax statements. Encloses optional items in syntax statements. Type only the information within the brackets, not the brackets themselves. Represents an omitted portion of code sample. Encloses required items in syntax statements. Type only the information within the brackets, not the brackets themselves. Distinguishes short comments in C++ and Java programming code. Distinguishes long comments in C++ and Java programming code. Distinguishes long comments in C, C++ and Java programming code. Distinguishes comments in HTML, WAP & XHTML programming code.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

8
BO-EN-Python-20080613.pdf

Developer Training

Python
Contents
Introduction ............................................................12
What is Python?..............................................................................................................13 Why Python?.....................................................................................................................14 Design tradeoffs..............................................................................................................15 Growing user base........................................................................................................16 Common Use Cases for Python..........................................................................17 Development environment..................................................................................18 Interactive prompt.......................................................................................................19 Hello world..........................................................................................................................20

Python on S60 .........................................................21

S60 Python (PyS60) consists of..........................................................................22 Deployment of Python programs (1/2)......................................................23 Deployment of Python programs (2/2)......................................................24 S60 Python compatibility.......................................................................................25 Active object Framework (1/2).......................................................................26 Active object Framework (2/2).......................................................................27 Application Framework...........................................................................................28 S60 screen components in Python.................................................................29 Forms ......................................................................................................................................30 Listboxes...............................................................................................................................31 Dialogs....................................................................................................................................32 Text............................................................................................................................................33 Canvas (1/2) .......................................................................................................................34 Canvas (2/2) .......................................................................................................................35

Programming Basics .............................................36

Standard types.................................................................................................................37 Strings.....................................................................................................................................38 Indexing and slicing....................................................................................................39 Lists............................................................................................................................................40 Tuples......................................................................................................................................41 Dictionaries.........................................................................................................................42 Control flow........................................................................................................................43 For loop..................................................................................................................................44 if-then-else..........................................................................................................................45 Functions..............................................................................................................................46 Object model.....................................................................................................................47 Classes 101..........................................................................................................................48 Modules.................................................................................................................................49 File manipulation..........................................................................................................50 Files and directories.....................................................................................................51 Standard library miscellanea...............................................................................52 Other useful functionality.......................................................................................53

BO-EN-Python-20080613.pdf

Python

Zen of Python....................................................................................................................54 Documenting code ......................................................................................................55 Unit testing..........................................................................................................................56 Exception handling......................................................................................................57 Reserved Keywords .....................................................................................................58

Python S60 Modules.............................................. 59

Camera Module...............................................................................................................60 Audio Module....................................................................................................................61 Databases.............................................................................................................................62 Databases - Contacts ...................................................................................................63 Databases - Calendar...................................................................................................64 Other modules 1/2.......................................................................................................65 Other modules 2/2.......................................................................................................66

Python Sockets ....................................................... 67

Socket programming 1/4.......................................................................................68 Socket programming 2/4.......................................................................................69 Sockets: Bluetooth 3/4..............................................................................................70 Sockets 4/4..........................................................................................................................71

Course summary .................................................... 72 Thank you. ............................................................... 73

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

10
BO-EN-Python-20080613.pdf

Python

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

11
BO-EN-Python-20080613.pdf

Python

Introduction

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

12
BO-EN-Python-20080613.pdf

Python

What is Python?

Python is a general purpose programming language optimized for rapid application prototyping. Because it is interpreted during execution, it is not as fast as compiled languages such as C++.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

13
BO-EN-Python-20080613.pdf

Python

Why Python?

The number of Python users is growing. It is portable and extensible, it integrates well with native C++ environments, it has large standard library with ready made functions, and still it is easy to learn and use. SWIG (Simplified Wrapper and Interface Generator) allows a developer to wrap C/C++ functions for use with scripting languages, such as Python. BoostPython is a C++ library which enables seamless interoperability between C++ and the Python programming language.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

14
BO-EN-Python-20080613.pdf

Python

Design tradeoffs

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

15
BO-EN-Python-20080613.pdf

Python

Growing user base

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

16
BO-EN-Python-20080613.pdf

Python

Common Use Cases for Python

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

17
BO-EN-Python-20080613.pdf

Python

Development environment

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

18
BO-EN-Python-20080613.pdf

Python

Interactive prompt

Running bt_console is easy from S60 and is recommend way to test out functions. Do not use it for lengthy programs that might crash the console since all your data is lost if console raises exception Another way of stepping through the code is pdb.py (Python debugger supplied with python S60 package).

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

19
BO-EN-Python-20080613.pdf

Python

Hello world

Lets see if the environment has been set up correctly by creating helloworld program and running it on both PC and S60. All PCs need a bluetooth module (eighter built-in or dongle) that is used for connecting PC to Mobile phone.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

20
BO-EN-Python-20080613.pdf

Python

Python on S60

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

21
BO-EN-Python-20080613.pdf

Python

S60 Python (PyS60) consists of

When developing python scripts they are run under the execution environment, but it is possible to create stand-alone python scripts using py2sis utility program to make symbian installation files (.SIS) that have a generated application executable which enables users to start python scripts without explicitly starting the execution environment. This way Python scripts appear to users like any other application in the system and the user is unaware that the implementation was made with Python. Python installer will allow .py modules to be installed as runnable scripts or as libraries that can be imported for use of other scripts.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

22
BO-EN-Python-20080613.pdf

Python

Deployment of Python programs (1/2)

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

23
BO-EN-Python-20080613.pdf

Python

Deployment of Python programs (2/2)

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

24
BO-EN-Python-20080613.pdf

Python

S60 Python compatibility

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

25
BO-EN-Python-20080613.pdf

Python

Active object Framework (1/2)

Consult S60 SDK documentation on how active objects and the active framework works on Symbian.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

26
BO-EN-Python-20080613.pdf

Python

Active object Framework (2/2)

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

27
BO-EN-Python-20080613.pdf

Python

Application Framework

If you want to create a non application framework python scripts (servers) you can call e32.start_server at the start of your program.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

28
BO-EN-Python-20080613.pdf

Python

S60 screen components in Python

Above image is normal view of S60 applications. Python supports three different view types for applications: normal, large and full screen. To set another view type, programmer can set appuifw.app.screensize = normal ; large ; full Please note that the application icon cannot be set from Python. Only the Py2sis utility allows you to do this.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

29
BO-EN-Python-20080613.pdf

Python

Forms

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

30
BO-EN-Python-20080613.pdf

Python

Listboxes

To load icons you need to use Icon class that can read Symbian multibitmap format (.MBM). Check the python API reference to see how to do this.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

31
BO-EN-Python-20080613.pdf

Python

Dialogs

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

32
BO-EN-Python-20080613.pdf

Python

Text

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

33
BO-EN-Python-20080613.pdf

Python

Canvas (1/2)

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

34
BO-EN-Python-20080613.pdf

Python

Canvas (2/2)

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

35
BO-EN-Python-20080613.pdf

Python

Programming Basics

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

36
BO-EN-Python-20080613.pdf

Python

Standard types

Arbitary size integers is a speciality of Python. E.g. in C++ the int is limited to current machine word of your environment (32bit in ARM). In Python the following initialization is allowed and perfectly valid but would overflow in many other programming environments fiveBillion = 5*10**9 oneMillion = 1*10**6 print fiveBillion *oneMillion Division operation on integer depends on the Python version. Check the documentation to see wheter you should use / - operator or // - operator.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

37
BO-EN-Python-20080613.pdf

Python

Strings

Multiline spanning is widely used when commenting code. See extra slides about commenting and documenting conventions with Python.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

38
BO-EN-Python-20080613.pdf

Python

Indexing and slicing

Slicing and indexing is a very powerful tool when extracting data out of strings, though strings are not the only data type that supports it; slice can be used to extract data out from any kind of list like structure (string/list/tuple). For more powerful string handling look up Regular Expression module from the documentation.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

39
BO-EN-Python-20080613.pdf

Python

Lists

The difference between append and extend might not be clear at first. Consider the following example: myList = [1,2,3] myList.append([4,5]) #appends a single element myList.extend([6,7]) #extends with elements print myList [1, 2, 3, [4, 5], 6, 7]

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

40
BO-EN-Python-20080613.pdf

Python

Tuples

Examples of structure: #simple tuple containing 4 members a = (1,2,3,4) print a (1,2,3,4) # tuple containing tuple a and a string hello b = (a,hello) print b ((1,2,3,4),hello) #tuple containing two arrays c = ([1,2],[3,4]) print c[1] (3,4) #unpacking a tuple d,e = c print d [1,2] # tuples are immutable hence trying to assign to it c[1] = 5 # creates runtime error

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

41
BO-EN-Python-20080613.pdf

Python

Dictionaries

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

42
BO-EN-Python-20080613.pdf

Python

Control flow

Python does not use braces to create a block scope, instead Python uses indentation to create a code block. Indentation is normally done with whitespaces and you should set your editor to insert spaces instead of TAB delimitters to ensure portability of your code. Indentation is four spaces to create a new code block. It has been widely argued whether this is a good or bad desicion, use it for a while and you will not even notice the missing braces. Note that no delimitter is required to end command, for example ,no ; at the end of line. Python command sequences end in whitespace or in explicit delimitter of ;. Commands expanding to multiple lines end with newline char.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

43
BO-EN-Python-20080613.pdf

Python

For loop

How to read for loops in Python: for every element in the list do the following lines for fruit in fruits: print is + fruit + ripe?

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

44
BO-EN-Python-20080613.pdf

Python

if-then-else

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

45
BO-EN-Python-20080613.pdf

Python

Functions

Here you see the problem of late binding, since the functions can take any type of object as a parameter the environment cannot do type checking until the command is being executed. Only way environment can handle such situations is to raise TypeError exception. Object model and late binding is discussed in the following slides.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

46
BO-EN-Python-20080613.pdf

Python

Object model

Python is a full object language - even the built-in types are objects and what programmer sees are instances of these objects. #Easy example to prove that integer is truely an object dir(1) # will output all the functions of integer object type

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

47
BO-EN-Python-20080613.pdf

Python

Classes 101

def __init__(self) Defines the constructor for class. Unlike C++ you cannot overload constructor definitions. Only single definition can be defined. def __call__(self) Makes this a callable object, if the object has been constructed and user calls the Function operator again it will lead to calling of this function. There are various useful standard functions to be implemented for a class. One very nice is the string representation of the class: def __str__(self): return this is how I like to be printed out

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

48
BO-EN-Python-20080613.pdf

Python

Modules

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

49
BO-EN-Python-20080613.pdf

Python

File manipulation

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

50
BO-EN-Python-20080613.pdf

Python

Files and directories

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

51
BO-EN-Python-20080613.pdf

Python

Standard library miscellanea

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

52
BO-EN-Python-20080613.pdf

Python

Other useful functionality

Iterators and generators seem like a complex idea but provide an easy solution for doing loops and avoiding return values being lost into void. Example: def fruitsInFreeze(): fruits = ['apple','orange','banana'] for f in fruits: yield f for fruit in fruitsinFreeze(): print fruit apple orange banana

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

53
BO-EN-Python-20080613.pdf

Python

Zen of Python

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

54
BO-EN-Python-20080613.pdf

Python

Documenting code

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

55
BO-EN-Python-20080613.pdf

Python

Unit testing

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

56
BO-EN-Python-20080613.pdf

Python

Exception handling

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

57
BO-EN-Python-20080613.pdf

Python

Reserved Keywords

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

58
BO-EN-Python-20080613.pdf

Python

Python S60 Modules

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

59
BO-EN-Python-20080613.pdf

Python

Camera Module

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

60
BO-EN-Python-20080613.pdf

Python

Audio Module

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

61
BO-EN-Python-20080613.pdf

Python

Databases

e32dbm databases deliver the promise of working in the same way as regular DBM Python modules. You can even load anydbm in S60, and the e32 backend is automatically selected. e32dbm is based on e32db, a SQL-based mini storage system supplied by Symbian OS. You can use either, depending on which semantic (DBM or SQL) is more convenient for you.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

62
BO-EN-Python-20080613.pdf

Python

Databases - Contacts

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

63
BO-EN-Python-20080613.pdf

Python

Databases - Calendar

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

64
BO-EN-Python-20080613.pdf

Python

Other modules 1/2

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

65
BO-EN-Python-20080613.pdf

Python

Other modules 2/2

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

66
BO-EN-Python-20080613.pdf

Python

Python Sockets

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

67
BO-EN-Python-20080613.pdf

Python

Socket programming 1/4

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

68
BO-EN-Python-20080613.pdf

Python

Socket programming 2/4

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

69
BO-EN-Python-20080613.pdf

Python

Sockets: Bluetooth 3/4

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

70
BO-EN-Python-20080613.pdf

Python

Sockets 4/4

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

71
BO-EN-Python-20080613.pdf

Python

Course summary

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

72
BO-EN-Python-20080613.pdf

Python

Thank you.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

73
BO-EN-Python-20080613.pdf

Python

Lab XXXXX.cb1
Introduction
Title: Overview: HelloWorld In the lab, the classic HelloWorld program is written in Python. More importantly, students learn how to run Python programs in the S60 emulator and device. To learn how to: Compatible SDK(s): Starter Code Provided: Estimated Time To Complete: Edit and write Python programs Run programs in the S60 emulator Run programs in the S60 device

Objectives:

Nokia C++ S60 3rd Edition, Feature Pack 2 SDK No 30 minutes Solution Code Provided: Yes

Lab Instructions
Exercise 1 Preliminary steps Task 1.1 Checks
1. 2. Write Python script, which prints HelloWorldon the screen using any available editor. Copy the script to the C:\python folder (<Symbian installation folder>\epoc32\winscw\c\python). If you do not know the path of the Symbian installation folder, open a command prompt and type devices. After that, type in devices info@<default device id>. For example, below the installation path is the same as root, i.e., C:\S60\devices\s60_3rd_fp2_SDK. Note that this course assumes you are using the S60 3rd Edition SDK and Python S60 SDK 1.4.3. Go to http://sourceforge.net for a list of the available Python SDKs and their compatibility with S60 SDKs.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

75
BO-EN-Python-20080613.pdf

Python

Task 1.2 Running in the emulator


1. Launch your emulator either from the Start menu or in the command prompt by typing epoc. Launch the Python interpreter from Installations.

2.

After starting Python script shell, open the application menu using the left softkey and execute Run script. Select your HelloWorld to be executed. The solution folder also contains a GUI version of HelloWorld, which will be studied later.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

76
BO-EN-Python-20080613.pdf

Python

Task 1.3 Running in the device


1. If you are using S60 3rd Edition, you can use Ensymble developer utilities to create and sign a .SIS file (Symbian Installation System). The .SIS package allows you to install the Python script file to a mobile device. For details on how to create a .SIS package, go to www.nbl.fi. If you are using S60 2nd Edition, create a .SIS installation package with the py2sis tool, which is part of the Python SDK. The tool creates a standalone Python application that can be executed in the device like a native application. Read the *readme*.txt files for help; they are located in epoc32\tools\py2sis folder. Transfer and install the created .SIS package to your mobile device. Execute your script in the phone.

2.

3. 4.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

77
BO-EN-Python-20080613.pdf

Python

Lab XXXXX.cb12
Introduction
Title: Overview: Objectives: Phonebook application This lab is our first GUI Python program. In addition, some S60 Python module APIs are used. To learn how to: Compatible SDK(s): Starter Code Provided: Estimated Time To Complete: Use the S60 application framework Use S60 Python module APIs

Nokia C++ S60 3rd Edition No 45 minutes Solution Code Provided: Yes

Lab Instructions
Exercise 2 Phonebook application Task 2.1 S60 application framework
1. 2. 3. 4. 5. The solution folder contains UiTest.py script, which shows examples of how to use S60 GUI controls. Refer to this folder for guidance, if needed. Import the application framework and e32 modules to your program. Yield execution to any outstanding active objects. Lock the AO scheduling. Define a menu. You may have for example: a. b. c. 6. 7. Dial functionality; SMS functionality; About functionality.

At this point, define the empty functions for your menu. Define a listbox, which shows a list of names. Define also the list yourself. d. You need a listbox observer for listbox. Use any function as an observer. The function does not have to do anything so you may implement is by writing just pass in function defitnion.

8. 9.

Add the listbox to your UI framework. Store the previous application title and define a new title. In the same way, store the previous exit handler and replace that with a new one.
Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

78
BO-EN-Python-20080613.pdf

Python

e. f.

In the new exit handler, restore the old exit handler and application title; Call signal() for the AO lock.

10. Call wait() for the AO lock. 11. Run and test. You cannot send messages or make phone calls yet.

Task 2.2 Calling module APIs


1. Now implement Dial, SMS, and About functionality: a. b. c. 2. Dial: Call dial() in the telephone. The number is the current list box number. SMS: Query the message content from the user. Send the message to the current listbox number. About: Print the information data or your application.

Test your program.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

79
BO-EN-Python-20080613.pdf

Python

Lab XXXXX.cb13
Introduction
Title: Overview: Objectives: Word guessing game The game implemented in this exercise introduces basic Python programming issues; there is no emphasis on GUI yet. To learn how to: Compatible SDK(s): Starter Code Provided: Estimated Time To Complete: Use Python types Use Python programming structures Use modules and types from modules

Nokia C++ S60 3rd Edition No 45 minutes Solution Code Provided: Yes

Lab Instructions
Exercise 3 Game implementation Task 3.1 Modules, types, programming structures
1. 2. 3. 4. 5. 6. Import Random from the random module. Define an empty list of words, which a player tries to guess. In the main function, occupy the word list with some elements (strings). Select a random word to be the solution. Define a hint string that is shown to the user. Initially, it can show the first character of the solution. Define a loop, where as long as the solution length has not been exceeded, the following will occur: g. h. i. j. A hint is printed; The player inputs a guess character; The correctness of the guess is checked. Before the check, the guess is converted to lowercase characters. If the answer is incorrect, the next hint character is provided.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

80
BO-EN-Python-20080613.pdf

Python

Task 3.2 Running


1. Run and test your script.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

81
BO-EN-Python-20080613.pdf

Python

Lab XXXXX.cb1
Introduction
Title: Overview: Objectives: Bluetooth sockets More complicated functionality will be added to the exercise. To learn how to: Compatible SDK(s): Starter Code Provided: Estimated Time To Complete: Use S60 sockets Use Bluetooth sockets

Nokia C++ S60 3rd Edition SDK No 45 minutes Solution Code Provided: Yes

Lab Instructions
Exercise 4 Bluetooth sockets Task 4.1 Sockets programming
1. 2. 3. Use the UI framework skeleton from the previous exercise. You need four functions: connect(), recv(), send(), and close(). Connect() a. b. c. d. e. f. 4. Recv() g. 5. Send() h. i. 6. Close() j. k. Close the socket. Close the application.
Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

Create a streaming BT socket. Use the device and service discovery protocol to find devices and services. Print out information about found devices and services. If any services are found, create a choicelist. Sort the services and create a popup menu, where you show the sorted list of available services. Define the host to be the device selected by the user. Try to connect to the selected device (and service).

Just pass.

Print the message that the data is sent. Send the data to the socket.

82
BO-EN-Python-20080613.pdf

Python

7.

Run and test. Start the Bluetooth service in your PC and use HyperTerminal to connect to the Bluetooth COM port. Start the Python program in your mobile device and browse the PC device.

Nokia 2008. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation

83
BO-EN-Python-20080613.pdf

Potrebbero piacerti anche