【问题标题】:Variable scope in python codepython代码中的变量范围
【发布时间】:2016-09-24 08:51:06
【问题描述】:
from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")
    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")

def dead(why):
    print why
    exit(0)

1) gold_room 方法内部如何调用dead 方法,因为dead 方法的定义在调用语句下面?

2) 变量how_much 如何在其范围之外访问?它在缩进块内声明和初始化 -

 if "0" in choice or "1" in choice:
        how_much = int(choice)

而且根据我的理解,它的作用域应该到这里就结束了。那么在这种情况下如何进一步使用它 - if how_much &lt; 50

【问题讨论】:

    标签: python python-2.7 scope


    【解决方案1】:

    Python 中没有内置的“死”方法。解释器之所以告诉你没有定义,是因为你没有定义。

    Python 没有块作用域。从那时起,函数内部定义的变量都是可见的,直到函数结束。

    在第一个问题更改后编辑函数的定义顺序无关紧要,只要它们都是在它们被调用时定义的 .据推测,在定义了两个函数之后,您在调用 gold_room 的模块末尾有一些代码。

    【讨论】:

    • 好的,我忘了定义dead 方法。现在请查看问题代码和第 1 点中的编辑。你能回答吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多