如何在def函数内打印

2024-05-19 17:03:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序:

games = ['tlou', 'hitman', 'rainbow 6', 'nba2k']
print(games)
def list_o_matic(inp):
    if inp == "":
        games.pop()
        return "the game" + inp + "was deleted"
    elif inp in games:
        games.remove(inp)
        return "the game" + inp + "was removed"
    elif inp != games:
        games.append(inp)
        return "the game" + inp + "was added"
while True:
    if not games:
        print("goodbye!")
        break
    else:
        inp = input("write the name of the game: ")
        if inp == 'quit':
            print("goodbye!")
            break
        else:
            list_o_matic(inp)
            print(games)

它的作用是你写一个名字(这里是一个视频游戏的名字),然后检查它是否在列表中,如果不在列表中,它会添加它,如果是这样的话,程序会删除它。 问题是输出没有函数中的消息,我不知道为什么。在


Tags: the程序gamereturnifelsegameslist
2条回答

您可以在代码print(list_o_matic(inp))中进行修改,因为您的函数已经返回了一个字符串。在

由于您是从list_o_matic返回消息,所以您应该只打印来自调用方的返回值:

games = ['tlou', 'hitman', 'rainbow 6', 'nba2k']
print(games)
def list_o_matic(inp):
    if inp == "":
        games.pop()
        return "the game " + inp + " was deleted"
    elif inp in games:
        games.remove(inp)
        return "the game " + inp + " was removed"
    elif inp != games:
        games.append(inp)
        return "the game " + inp + " was added"
while True:
    if not games:
        print("goodbye!")
        break
    else:
        inp = input("write the name of the game: ")
        if inp == 'quit':
            print("goodbye!")
            break
        else:
            print(list_o_matic(inp))
            print(games)

或者,如果您希望按标题所示在函数内打印消息,则打印消息时不返回:

^{pr2}$

相关问题 更多 >