[Tutor] Newbie python programmer here.

David Broadwell dbroadwell@mindspring.com
Sun May 18 16:55:01 2003


TERRENCE-jarrod wrote:

<quote>
Hi everyone, I just started programming in python and just started
subscribing to this mailing list as well. I look forward to gathering
and sharing ideas and learning too. Anyhow, here is my first question.
I have a function that is supposed to reverse all the letters in a word.
That is what I want it to do anyhow. I can't seem to get it right. What
am I doing wrong?

def reverse(name):
    name = "aname"
    for i in name:
           print i[-1]

</quote>

Well: let's look at what your code really does:

a
n
a
m
e

First you define reverse as being called with name, yet in the next line,
overwrite it with a string. Not good if you intend to reverse anything but
aname, but not bad as a testing idea, just skip the calling with name. It
iterates through it forward, not bad that is one way.

def reverse(): or skip specifically assigning name to 'aname' and call
reverse('aname') instead.

So given the string 'aname' how can we iterate through it backwards?

What do we know about it:

>>> name = 'aname'
>>> len(name)
5

Hm, 5 units in length.

How about:
>>> length = len(name)
>>> while length > 0:
      # print the character between length and length-1
	print name[length-1:length]
	length = length -1 # we've been here decrease length

e
m
a
n
a

which as a function looks like:

def reverse(name):
    ''' this function reverses a string and prints it. '''
    length = len(name)
    while length > 0:
        # print the character between length and length-1
        print name[length-1:length]
        length = length -1 # we've been here decrease length
    return 1

Well I did skip a few steps to get to that logic. So I recommend starting up
the interpreter, and seeing what slices can do for you. There are about as
many ways to solve this problem as there are programmers. Complete with
using the built in list.reverse() str.join, but slices are strait-forward
and easy to test.

Also, I recommend at least as many good tutorials as you can read starting
on www.python.org. Good luck.

> p.s. this mail will always have the name Terrence on it my name is Jarrod.
Why?

--

David Broadwell