如何使用函数作为变量?

时间:2019-07-07 16:57:04

标签: python

因此,我尝试做一个小的Hangman程序作为练习,但是遇到一个问题:如果我定义一个函数(使用return语句),然后将其用作另一个函数的参数,则会得到TypeError

def two_player_hangman():
    player_1_input = input(print("What is your word? "))
    player_1_list = list(player_1_input)
    return player_1_list


def blank_space_creator(in_list1):
    word_list = []
    for a in range(0, len(in_list1)):
        word_list.append("-")
    return word_list

a = blank_space_creator(two_player_hangman)
print(a)

如果我输入单词'hi',我应该得到['-', '-']。 但是相反,它引发:TypeError: 'function' object is not iterable

3 个答案:

答案 0 :(得分:1)

您需要替换为:

a = blank_space_creator(two_player_hangman())

要考虑two_player_hangman的输出。

答案 1 :(得分:0)

您能否在调用它时在“ two_player_hangman”函数中添加括号:

a = blank_space_creator(two_player_hangman()) print(a)

答案 2 :(得分:0)

我对您的代码进行了如下更改:

def two_player_hangman():
    player_1_input = input("What is your word? ") # you don't need to provide print method inside of the input method
    return player_1_input


def blank_space_creator(in_list1):
    word_list = []
    for a in in_list1: # converting a string into a list and then counting the number of elements in the list is not efficient here, instead you can directly iterate over a string
        word_list.append("-")
    return word_list

a = blank_space_creator(two_player_hangman()) # you have to call the method
print(a)