0

I am practicing with "Think Python", Exercise 8.1 that:

"Write a function that takes a string as an argument and displays the letters backward, one per line."

I am able to do this question, by using banana as an example to print each letter per line.

index = 0
fruit = "banana"
while index < len(fruit):
    letter = fruit[len(fruit)-index-1]
    print letter
    index = index + 1

However, I would like to generalize the situation to any input words and I got the problem, my code is

index = 0
def apple(fruit):
    while index < len(fruit):
        letter = fruit[len(fruit)-index-1]
        print letter
        index = index + 1

apple('banana')

The corresponding errors are:

Traceback (most recent call last):
  File "exercise8.1_mod.py", line 21, in <module>
    apple('banana')
  File "exercise8.1_mod.py", line 16, in apple
    while index < len(fruit):
UnboundLocalError: local variable 'index' referenced before assignment

I think there should be problems concerned with the function arguments used. Any helps will be appreciated.

nam
  • 215
  • 2
  • 11

3 Answers3

1

This should probably work better:

def apple(fruit):
    for letter in fruit[::-1]:
        print letter

apple('banana')

This works by indexing the string in reverse, a built in python function known as slicing.

Reverse a string in Python

Community
  • 1
  • 1
beiller
  • 3,105
  • 1
  • 11
  • 19
  • thx beiller, I learn from your statement, fruit[::-1], it is neat and sound pretty for me~! – nam Jul 19 '14 at 13:59
0

You need to assign a value to index before you use it.

def apple(fruit):
    index = 0  # assign value to index
    while index < len(fruit):
        letter = fruit[len(fruit)-index-1]
        print letter
        index = index + 1
apple("peach")
h
c
a
e
p
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thank you very much for your comment on *assign value to index*. My program gets run. Thx =] – nam Jul 19 '14 at 13:43
0

your program got error due to your accessing a global variable in your method and trying to change its value

index = 0
def apple(fruit):
    .....
    index = index + 1
    ....    
apple('banana')

this give you error UnboundLocalError: local variable 'index' referenced before assignment

but if you give

def apple(fruit):
        global index
        .....
        index = index + 1
        .... 

this produces correct result

in python we have Global variable and Local variables

please go throught this

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as global.

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
  • Thank you very much for your detailed explanation on local and global variables. It does help a lot! – nam Jul 19 '14 at 13:42