我有这个程序:
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)
它的作用是你写一个名称(在这种情况下是视频游戏名称(,它会检查它是否在列表中,如果没有,它会添加它,如果是这样,程序会删除它。 问题是输出没有函数中的消息,我不知道为什么。
由于您从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)
或者,如果您希望按照标题的建议在函数中打印消息,请打印消息而不返回它:
games = ['tlou', 'hitman', 'rainbow 6', 'nba2k']
print(games)
def list_o_matic(inp):
if inp == "":
games.pop()
print("the game " + inp + " was deleted")
elif inp in games:
games.remove(inp)
print("the game " + inp + " was removed")
elif inp != games:
games.append(inp)
print("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)
您可以在代码print(list_o_matic(inp))
中进行修改,因为您的函数已经返回了一个字符串。