Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将一个字符串从一个函数输入到另外两个函数中,并用python打印它?_Python - Fatal编程技术网

如何将一个字符串从一个函数输入到另外两个函数中,并用python打印它?

如何将一个字符串从一个函数输入到另外两个函数中,并用python打印它?,python,Python,我正在创建一个文本冒险游戏,如果用户键入“x”或“examine”,它将打印房间的描述(存储在a函数中的字符串中) 代码如下: 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, eas

我正在创建一个文本冒险游戏,如果用户键入“
x
”或“
examine
”,它将打印房间的描述(存储在a函数中的字符串中)

代码如下:

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
”来打印该房间的描述,但我无法链接这些函数。

尝试
a=raw\u input('>>)
然后
a=a.strip()


你需要一个标签,而不需要()

我认为正确的解决方案是创建教室,它的实例将存储房间描述,也许还有其他东西,也许是其他房间的门列表(你不会只有一个房间,是吗?)

而且这个类还应该有
look
方法做你已经知道的事情

我认为应该将当前房间存储在某个全局变量中,当需要当前房间的描述时,只需访问该变量,获取房间对象并调用其
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语句

修复代码缩进抱歉,我没有正确粘贴它。但是它在编辑器中是缩进的。请在代码中也修复缩进。好的,我修复了它。谢谢达德普的编辑,还有那个贴出答案并将其删除的家伙。我更改了它,使look函数返回变量'bla'。谢谢,这似乎比我以前做的要容易得多。
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