[Tutor] Newbie python programmer here.
Alan Gauld
alan.gauld@blueyonder.co.uk
Mon May 19 16:20:02 2003
> 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):
This defines a function called reverse which takes a parameter 'name'.
Thus to use it you call:
reverse('Jarrod')
> name = "aname"
This overwrites the name with 'aname' which I assume you just
put there to make testing easier?
> for i in name:
> print i[-1]
This takes each letter in 'aname' and prints it.
Try this approach.
Start at the end of the string and work back to zero:
def reverse(name):
index = len(name)
while index > 0:
print name[index], # comma stops newline
index = index - 1
That will print the letters with spaces in between but
in the order we want.
To avoid the spaces we can use a temporary string:
def reverse(name):
index = len(name) - 1 # subtract 1 to account for zero start
result = "" # start with it empty
while index >= 0:
result = result + name[index] # add the current letter
index = index - 1
print result
To make the function more reusable you might also want to return the
result rather than printing it, like so:
def reverse(name):
index = len(name) - 1 # subtract 1 to account for zero start
result = "" # start with it empty
while index >= 0:
result = result + name[index] # add the current letter
index = index - 1
return result
Now we can use it like this:
>>> print reverse('fooey')
yeoof
>>> temp = reverse('Terrence')
>>> print temp
ecnerreT
Its usually a good idea to separate printing from calculations
or operations on data.
HTH,
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld