python - 不在 Python 中执行的函数

标签 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/

相关文章:

python - 查找一个矩阵是否是另一个矩阵的子矩阵的有效方法?

python - Sublime text 3 运行 python 脚本并在(Ubuntu)之后保持交互模式

python - 导入错误:没有名为 'mirror' 的模块

python - 这个 python 脚本会按预期工作吗?我想让它把随机数代入一个等式直到它得到 187.2

python - 在不同的键上多次使用字典列表排序 - 是否保证保留顺序?

python - Django 应用程序的典型内存使用情况

Python 中止后无限循环

python - 如果 stdin 包含 EOF,如何知道它何时为空?

python - LZ77压缩保留字节 "< , >"

python - 如何实现 glob.glob