Reputation: 215
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.
Upvotes: 0
Views: 1037
Reputation: 8692
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.
Upvotes: 0
Reputation: 180411
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
Upvotes: 0
Reputation: 3135
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.
Upvotes: 1