gpt4 book ai didi

python - 如何将 1 个函数中的字符串输入到另外 2 个函数中,并在 python 中打印它?

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:55 24 4
gpt4 key购买 nike

我正在创建一个文本冒险游戏,并且希望如果用户键入“x”或“examine”,它会打印一个文本冒险游戏的描述room(存储在函数内的字符串中)

这是代码:

def look(dsc):
print(dsc)


def usr_input(dsc):


a = input(">>> ")
if a == "examine" or a == "x":
look(dsc)
if a == "help":
print("north, n, east, e, south, s, west, w, up, u, down, d, inventory, i, examine, x")
if a == "north" or a == "n" or a == "forwards":
return "north"
if a == "east" or a == "e" or a == "right":
return "east"
if a == "south" or a == "s" or a == "backwards":
return "south"
if a == "west" or a == "w" or a == "left":
return "west"
if a == "up" or a == "u":
return "up"
if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False


def room_00():
room_description = "Description goes here"
print(room_description)
usr_input(room_description)


room_00()

基本上,每当用户键入 x 时,我都需要函数“look”来打印该房间的描述,但我无法链接这些函数。

最佳答案

你的代码似乎运行没有任何问题,忽略上面的人,Python 3 确实需要括号来进行打印调用。

它返回了一个回溯,因为在第 28 行,您在不提供参数的情况下调用了 usr_input() 函数。

您可以通过如下定义函数来解决此问题:

def look(dsc=''):
print(dsc)

这会将空字符串传递给函数,除非您将其传递给您自己的字符串。

另一个问题是您使用的是原始 if 语句。所以最后的评估在这里:

if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False

转到else分支,因为x既不是“down”也不是“a”,你应该用elif替换第一个下面的所有if语句,并保留最后一个else

关于python - 如何将 1 个函数中的字符串输入到另外 2 个函数中,并在 python 中打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44024695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com