PYTHON:如何创建一个接收变量输入并传递给另一个函数的函数

3 投票
3 回答
1819 浏览
提问于 2025-04-16 14:28

我正在使用《艰难的Python学习》,第35个练习的额外任务是要简化。我想创建一个函数,让用户输入一个变量,然后把这个变量返回给其他函数。

如果我说得不太清楚……

    def action():
        next = raw_input (">> ")
        return next

    def start():
    print"""
You are in a dark room.
There is a door to your right and left.
Which one do you take?"""

    action()

    if next == "left":
        bear_room()
    elif next == "right":
        cthulu_room()
    else:
        dead("You stumble around the room until you starve.")

当我这样运行时,它总是把next当作else处理。

3 个回答

1

你需要把调用 action() 的结果赋值给一个变量,比如说 next = action()。当 action() 执行完毕后,Python 就不再需要你在里面创建的 next 这个变量了,所以它会把它丢掉。如果你想在另一个函数中保留这个结果,可以把函数的结果赋值给一个变量(在这里就是在 start() 函数中的 next)。

祝你编程愉快!

1

我已经修改了你的语法。希望这能帮到你。

def action():
    nextt = raw_input (">> ")
    return nextt

def start():
    print"""
    You are in a dark room.
    There is a door to your right and left.
    Which one do you take?"""

def bear_room():
    print "You meet the bear..."

def cthulu_room():
    print "you meet the princess"

def dead(message):
    print message

def answ(nextt):
    if nextt == "left":
       bear_room()
    elif nextt == "right":
       cthulu_room()
    else:
       dead("You stumble around the room until you starve.")

start()
ok = action()
answ(ok)
2

你需要把函数返回的值存储到某个地方;一旦函数执行完毕,函数下面的小范围(也就是它的命名空间)就会消失,连同里面的next变量也会消失。我觉得你真正想要的是:

next = action()

这样一来,虽然函数的小范围被销毁了,但你仍然可以在程序的顶层保留一个next的副本。

如果你觉得Python的这个特性有点过于“破坏性”,相信我:如果每个函数都能独立成一个小世界,而不会对你定义的全局变量造成影响,管理复杂的程序会简单得多!

撰写回答