[Tutor] basic problem

Mac Ryan quasipedia at gmail.com
Fri Oct 7 00:37:18 CEST 2011


On Thu, 6 Oct 2011 22:11:37 +0000
ADRIAN KELLY <kellyadrian at hotmail.com> wrote:


> can someone spell out to me in (simply if possible) what this
> programme is doing.  i understand the concept of the "for" loop and
> what its doing with the message the user enters.  i just cant
> understand the VOWELS and how it keeps adding 1 letter to the
> message. thanks for looking A
>  
>   
> # this programme will adding something to everything the user
> #types by using a for loop

This program might have been intended to to so, but it actually does
not. Have you tried running it?

> #set values
> new_message=" "
> VOWELS="AEIOU"

This last line defines what vowels are. It defines it as a string, but
keep in mind that strings in python can be both handled like individual
object like in "print(text)" or like an ordered collection of
letters, like in "for letter in message" (more on this in a moment).

> message=raw_input ("Enter a message: ")
> for letter in message:

This is an example of the second way of handling strings (the proper
name for what is going on here is "iteration"): the last line will
instruct python to take one letter at a time, from left to right, from
the message, and do with it whatever is indented here below.

>     if letter.lower() not in VOWELS:

This is still an example of handling strings as ordered collections of
letters: basically it says to check if any letter in "VOWELS" is the
same as the letter being processed, in lower case.

Actually this is also an example of pointless operation: VOWELS has
been defined as "AEIOU" which are all capital letters. Since the
comparison is done between a letter from the user input in lower case
("letter.lower()") the condition will always be True, so this line
might well not be there.

>         new_message = new_message+letter

The idea behind this line is that you keep adding the letter to the end
of the message. The line works, but it's not an example of good python
code. An improvement might be to use:

new_message += letter

which is more common and more readable. But in python one seldom does
this kind of operation because strings are "immutable objects". In
other words even if the logic behind is to "add a character" what is
really going on behind the scenes is that the old version of
"new_message" is destroyed, and a new one will take its place. While
this is not a problem in this simple example, it is an expensive
process, so often it is preferable to store the various "additions" in
a list and merge them together only once, at the very end.
The syntax is:

''.join(['a', 'b', 'c'])

so in your program you would probably initialise an empty list first,
and then append the letters at each loop:

pool = []
for letter in message:
    pool.append(letter)
print ''.join(pool)

HTH!

/mac	   		  


More information about the Tutor mailing list