Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 10

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 10 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 102018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 10)

In the example below,we define a list of foods. Then we loop through the food items one byone, printing each of them to the screen.foods = [u"cheese", u"sausage", u"milk", u"banana", u"bread"]for x in foods:print xThis almost reads like English: ‘For x (every element) in (the list of)foods, print (the name of) x’. When executing this for loop, the resultingscreen shows ‘cheese’, ‘sausage’, ‘milk’, ‘banana’ and ‘bread’, one itemper line.If you want to loop over a range of numbers, you can use a specialrange() function.

This function produces a list of integers, from 0 tothe given maximum value.MESSAGES45for i in range(10):print iThis prints out the numbers from 0 to 9.Python Language Lesson: while loop and breakThe for loop is handy if you have a list of items or you know themaximum number of iterations beforehand. Sometimes, however, youwant to keep looping until some condition becomes true. The whileloop comes in useful in this case. This is how it looks:i = 10while i > 5:print xi = i - 1This example prints out 10, 9, 8, 7, 6 on the screen.

After the wordwhile, a conditional expression follows just as in an if statement.Another typical use is as follows:while True:ret = appuifw.query(u"Continue?", "query")if not ret:breakHere, the condition is always true, so the loop goes on foreverunless we force the execution out of it using the break statement. Thebreak statement makes the execution jump out of the loop instantly. Inthis example, we show a query dialog in each iteration. The loopingcontinues until the user cancels the dialog.3.3 MessagesLet’s introduce a second PyS60 module: messaging. It handles thesending of SMS (Short Message Service) and MMS (Multimedia MessagingService) messages.

Here we use only one function from the module:messaging.sms send().import messagingmessaging.sms_send("+14874323981", u"Greetings from PyS60")46GRAPHICAL USER INTERFACE BASICSTo be able to send an SMS we need to import the module messagingat the beginning of our script.

We only need to pass two parameters tothe function sms send (): the telephone number of the recipient as astring and the body of the message as a Unicode string.In this concluding example (Example 8), we combine the UI elementslearned in this chapter and the function for sending SMS messages into auseful little program.Imagine you are at home, your fridge is empty and your friend is onthe way home passing a grocery store. He does not know which items tobuy.

You want to send him a list of items by SMS while standing in frontof the fridge checking what is needed. Typing all the stuff into the phoneis just too much hassle and takes too much time.This is where your PyS60 program, the Shopping List Assistant, comesin. From a pre-defined list of items on your screen, you can select theitems needed using a selection list() dialog. A text input field letsyou type an additional greeting. After this, your shopping list is on its wayto your friend by SMS.Example 8: Shopping list assistantimport appuifw, messagingfoods = [u"cheese", u"sausage", u"milk", u"banana", u"bread"]choices = appuifw.multi_selection_list(foods,'checkbox',1)shoppinglist = ""for x in choices:shoppinglist += foods[x] + " "greetings = appuifw.query(u"Add some greetings?", "text", u"thanks!")if greetings:shoppinglist += greetingsprint "Sending SMS: " + shoppinglistmessaging.sms_send("+1234567", shoppinglist)appuifw.note(u"Shopping list sent")First we import the modules appuifw and messaging.

Next wecreate the list foods, which includes every possible food item that canbe missing from the fridge. This list can be extended by you to as manyelements as you want. Remember that the elements need to be Unicodestrings, that is, they must be prefixed with the ‘u’ character.In the next line, we generate our multi selection list() andpass foods to it. We also enable the find pane. This displays the selectionlist on the phone screen with all the goods, allowing us to select all theitems that need to be bought.

The result of our selection is stored in thevariable choices. It is a tuple that holds the indices of the selecteditems.A for loop reads the selected items from the foods list, based onthe indices of the selected items in choices. We start with an emptylist, shoppinglist, to which we add the required items during eachSUMMARY47iteration of the for loop. The += operator is a shorthand for the followingexpression:shoppinglist = shoppinglist + foods[x] + " "In the line following the for loop, we create a query dialog of type‘text’, meaning that the phone screen will show a text input field saying‘Add some greetings?’ with the initial word ‘thanks!’.

If the user choosesto add a greeting, the string is added to the shopping list.Finally, we want to send the shopping list by SMS. For this we usethe messaging.sms send() function to which we hand the mobilephone number of the recipient and the list shoppinglist.Once the phone has sent the SMS, we want a confirmation that theSMS with our shopping list has been sent. We do this by generating anote dialog of type ‘info’.And that is all.

Let’s hope our fridge will never be totally empty again.3.4 SummaryIn this chapter, we have introduced a set of native UI dialogs thatPyS60 offers. They got you involved with working examples of PyS60programming with relatively little code to write. The final exercise showedhow to combine several elements into a simple but useful application,the shopping list assistant.In Chapter 4, we introduce principles of application building and moveinto more fun applications.

In many examples throughout the book, youwill find these UI elements again and see how they can be part of a fullyworking application. At the same time, you learn how you can integratethem into applications of your own.Maybe you already have an idea of a simple application in whichsome of these UI elements can be used.

Why not try it out right away?4Application Building and SMS InboxPython for S60 gives you easy access to the framework for building userinterfaces on the S60 platform. Thanks to PyS60’s simple way of handlingthis, you learn how to build a real application that includes a title bar, amenu and some dialogs in around 15 lines of code!We start by describing how functions are defined in Python. We buildan application in Section 4.2, which also presents an overview of thestructure of a typical S60 application. In addition, this section introducesone of the most important concepts in PyS60, callback functions, whichlet you bind arbitrary actions to various events.

This concept comes inuseful when we show you how to add menus to your application.You may already be eager to start making real applications. InSection 4.3, we show how to handle strings. This is put to good useright away when we explain how to access the SMS inbox in Section 4.4.For example, we build fully functional applications which let you searchand sort your SMS messages easily. Finally, in Section 4.5, we presentan SMS game server that lets you and your friends play the game ofHangman using text messages.4.1 FunctionsThe Python scripts that you tried in the previous chapter are executedline by line.

Each line of code performs one action and, after the actionis finished, execution moves to the next line. This is a simple and robustway to perform tasks that straightforwardly proceed from the beginningto the end.However, if we want the user to decide what to do, instead of lettingthe program always perform the same operations in the same order,the code must be structured differently. Typically, this is the case when50APPLICATION BUILDING AND SMS INBOXan application has a graphical user interface that lets the user performdifferent actions by interacting with user interface (UI) elements.When using the S60’s framework for building user interfaces, theexecution does not progress deterministically line after line in the code.Instead, the user may launch specific tasks by pressing, say, specific keyson the mobile phone keyboard.

In this case, your job as an applicationdeveloper is to bind specific tasks to specific key events. When the userchooses a menu item or to quit, your application should execute a taskthat corresponds to such an event. For this purpose, you need to makefunctions of your own.In Example 1 (shown here once more as Example 9), we had threelines of code that were executed in sequence.

The second line triggereda text input field and the third line a popup note.Example 9: First PyS60 programimport appuifwword = appuifw.query(u"Type your name", "text")appuifw.note(u"Greetings from " + str(word))We could define a function and put the two lines of code insidethe function. This is what we do in Example 10, where the name ofthe function is askword(). Within a function, the execution proceedssequentially as usual. Functions are just a way to divide and structurecode into small chunks that are given a name.Example 10: First functionimport appuifwdef askword():word = appuifw.query(u"Type a word", "text")appuifw.note(u"The word was: " + str(word))Any time we want to carry out this task, that is, to execute these twolines of code, we just call the function askword():askword()askword()In this case, it asks for a word twice.You have been calling functions all the time in the previous chapters.For example:messaging.sms_send("+358...", u"Greetings from PyS60")appuifw.note(u"I love MobileArt")These lines from earlier examples, call the function sms send in themessaging module and the function note in the appuifw module.FUNCTIONS51Python Language Lesson: functionFunctions are a way to divide your code into independent tasks.

Afunction has a name and a body and it may be called. Optionally, afunction may take input variables, which are called parameters, and itmay return an output value. Here is an example:def add values(x, y):print "Values are", x, yreturn x + yThe keyword def starts the function definition. After the keyworddef comes the function name, in this case add values. In parentheses, follow the function parameters separated by commas.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее