2014-07-18 33 views
0

我与“认为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 

我想应该有与使用的函数参数有关的问题。任何帮助将不胜感激。

+5

只要把你的'index = 0'放在你的函数中(在它的开头)。 – BrenBarn

+0

@BrenBarn如果你解释他,他需要保持在里面,这样他才能了解局部和全局变量吗? :) –

回答

0

你的程序有错误,由于你在你的方法访问一个全局变量,并试图改变其价值

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

这个给你错误UnboundLocalError: local variable 'index' referenced before assignment

,但如果你给

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

这产生了正确的结果

在Python

我们有Global variableLocal variables

请到throught this

在Python,这只是一个函数里引用变量是隐含全球。如果一个变量在函数体内的任何地方被赋予了一个新的值,它被假定为一个局部变量。如果一个变量 曾经在函数内部被分配了一个新的值,那么这个变量是 隐式地是局部的,并且你需要明确地声明它是全局的。

+0

非常感谢您对本地和全局变量的详细解释。它确实有很大帮助! – nam

+0

@nam your welcome.glad帮助你:) –

1

这也许应该更好地工作:

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

apple('banana') 

这是通过索引反向字符串,一个建在称为切片Python函数。

Reverse a string in Python

+0

thx beiller,我从你的陈述,水果[:: - 1]中学习,它对我来说是整洁而美丽的! – nam

0

你需要你使用它之前将值分配给index

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 
+0

非常感谢您对*赋值给index *的评论。我的程序正在运行。Thx =] – nam

相关问题