我与“认为Python”练习,练习8.1是:的Python:传递函数参数字符串
“编写一个函数,采用一个字符串作为参数,并显示落后的字母,每行一个。”
我能够做到这个问题,以香蕉为例,每行打印每个字母。
index = 0
fruit = "banana"
while index < len(fruit):
letter = fruit[len(fruit)-index-1]
print letter
index = index + 1
不过,我想这种情况推广到任何输入的话,我得到了这个问题,我的代码是
index = 0
def apple(fruit):
while index < len(fruit):
letter = fruit[len(fruit)-index-1]
print letter
index = index + 1
apple('banana')
相应的错误是:
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
我想应该有与使用的函数参数有关的问题。任何帮助将不胜感激。
只要把你的'index = 0'放在你的函数中(在它的开头)。 – BrenBarn
@BrenBarn如果你解释他,他需要保持在里面,这样他才能了解局部和全局变量吗? :) –