简体   繁体   中英

Python: Passing Function Arguments for strings

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM