<分区>
我有一个程序在函数未定义时运行。当我将代码放入一个函数时,它不会执行它包含的代码。为什么?部分代码是:
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
标签 python
<分区>
我有一个程序在函数未定义时运行。当我将代码放入一个函数时,它不会执行它包含的代码。为什么?部分代码是:
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
最佳答案
问题1是你定义了一个函数(“def”是“define”的缩写),但是你没有调用它。
def new_directory(): # define the function
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
new_directory() # call the function
问题 2(您还没有遇到)是您在应该使用参数时使用了全局 (current_sandbox
)——在后一种情况下,您的函数通常是有用的并且甚至可以从另一个模块调用。问题 3 是不规则的缩进——使用 1 的缩进会导致任何必须阅读您的代码的人(包括您自己)发疯。坚持使用 4 并使用空格,而不是制表符。
def new_directory(dir_path):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
new_directory(current_sandbox)
# much later
new_directory(some_other_path)
关于python - 不在 Python 中执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1958134/