1

Python で関数を作成するのに問題があります。ユーザーがリストに単語を入力できるようにし、追加の単語を入力するかどうかをユーザーに尋ねる機能が欲しいです。ユーザーが「n」を入力した場合、関数がリストに入力された単語を返すようにしたいと思います。関数を実行すると、追加の単語を 2 回入力するかどうかをユーザーに尋ねます。また、リストは返されません。

def add_list(x):
    first_list = raw_input('Please input a word to add to a list ')
    x.append(first_list)
    response = None
    while response != 'n':
        response = raw_input('Would you like to enter another word? ')
        if response == 'n':
            print 'Here is the list of words'
            return x            
        else:
            add_list(x)


def main(): 
    add_list(x)


x = []
main()  
4

2 に答える 2

2

前述のように、コードが何も返さない理由は、実際に結果を出力しないためです。さらに、すでに 'n' と言った後でも、別の単語を入力したいかどうかを尋ね続ける理由は、再帰によるものです (つまり、ネストされた方法で関数を何度も呼び出しているという事実 (考えてみてください) ExcelでネストされたIF、それが役立つ場合:))。基本を理解したら、さらに詳しく読むことができますが、今のところは避けます:)

これは、何が起こっているのかを理解するのに役立つことを願ってコメント付きで、あなたが望むことをする何かの基本的なバージョンです:

def add_list():
    # Since you are starting with an empty list and immediately appending
    # the response, you can actually cut out the middle man and create
    # the list with the result of the response all at once (notice how
    # it is wrapped in brackets - this just says 'make a list from the
    # result of raw_input'
    x = [raw_input('Please input a word to add to a list: ')]

    # This is a slightly more idiomatic way of looping in this case. We
    # are basically saying 'Keep this going until we break out of it in
    # subsequent code (you can also say while 1 - same thing).
    while True:
        response = raw_input('Would you like to enter another word? ')

        # Here we lowercase the response and take the first letter - if
        # it is 'n', we return the value of our list; if not, we continue
        if response.lower()[0] == 'n':
            return x
        else:
            # This is the same concept as above - since we  know that we
            # want to continue, we append the result of raw_input to x.
            # This will then continue the while loop, and we will be asked
            # if we want to enter another word.
            x.append(raw_input('Please input a word to add to the list: '))

def main():
    # Here we return the result of the function and save it to my_list
    my_list = add_list()

    # Now you can do whatever you want with the list
    print 'Here is the list of words: ', my_list

main()
于 2012-11-18T00:42:43.877 に答える
0

私はあなたのプログラムを少し変更しました:

def add_list(x):
    first_list = raw_input('Please input a word to add to a list.')
    x.append(first_list)
    response = None
    while response != 'n':
        response = raw_input('Would you like to enter another word? ')
        if response.lower() in ['n','no']:
            print 'Here is the list of words:', x
            return x            
        else:
            x.append(response)

def main(): 
    returned_list = add_list(x)
    print "I can also print my returned list: ", returned_list


x = []
main() 

まず、再帰の必要はありません。代わりに、単にresponseリストに追加してくださいx。Pythonの優れた機能は、がresponseだけでなく、使用nに近いものであるかどうかを確認することです。n

if response.lower() in ['n','no']:

また、実際にリストをユーザーに印刷する行を編集しました。

print 'Here is the list of words:', x

最後に、リストを返却した後に印刷することもできます。編集されたをチェックしてくださいdef main():

于 2012-11-17T23:58:37.510 に答える