Wednesday, 16 January 2013

Example 13: SMS voter


Example 13: SMS voter

import messaging
PHONE_NUMBER = "+10987654321"
songs = (1, 3, 9, 11)
singers = "Tori, Kate, Alanis"
for song in songs:
for singer in singers.split(","):
msg = u"VOTE %d %s" % (song, singer.strip())
print "Sending SMS", msg
messaging.sms_send(PHONE_NUMBER, msg)
Here, the songs of interest are stored in the songs tuple. Your favorite
singers are given in the comma-separated string singers. Since we
want to go through every possible singer–song combination, we first
start looping through all songs and for each song we loop through all
singers.
However, we need to convert the singers string to a list for looping,
so we splice the string using the split() function. The split()
function produces the list ["Tori", " Kate", " Alanis"]. Note that
the names of Kate and Alanis are preceded by an unnecessary space.
We use the function strip() to get rid of leading white space.
Finally we construct a voting message with a template string. Since the
song identifiers are integers, they require the %d placeholder. Likewise,
the string placeholder %s is used for the names.
Be careful with the combination of loops and the sms send()
function, such as the one above. In real life, each SMS message costs
money and with loops you can easily send thousands of them! You might
want to try out this example without a SIM card in your phone, just to be
on the safe side.

No comments:

Post a Comment