为什么我的 Python 代码在 Visual Studio 代码中不正确 运行,但在 IDLE 中运行正常?

Why is my Python code not running correctly in Visual Studio Code, but runs fine in IDLE?

我目前正在学习 Python 并且遇到了一个非常奇怪的问题(至少对我来说是这样)。当我键入此代码时:

def search4vowels(word):
    """Display any vowels found in a supplied word."""
    vowels = set('aeiou')
    found = vowels.intersection(set(word))
    return bool(found)

在 IDLE 编辑 window 和 运行 它使用 IDLE,一切正常,我需要在提示符下输入我的函数才能启动。

但是,当我在 Visual Studio 代码和 运行 中编写相同的代码时,它使用 运行 Python 终端中的文件 我得到的选项是:

我也试过 Code 运行ner 扩展,它给了我一个空白的输出页面,无法输入函数。

例如search4vowels('galaxy')

我期望的输出应该是:True(因为单词中会出现元音,因此为真)

然而,没有任何反应。

您正在定义函数 search4vowels(),但是 Visual Studio 代码不知道如何 运行 它。

尝试在您的代码中添加:

def search4vowels(word):
    """Display any vowels found in a supplied word."""
    vowels = set('aeiou')
    found = vowels.intersection(set(word))
    return bool(found)

# This tells your code to run the function search4vowels():
if __name__ == '__main__':
    print(search4vowels('your word'))

这里是 the manual page 关于单词​​ "__main__"