[英]Python elif works in IDLE but not Visual Studio Code
我是 Python 新手,目前正在做我的第一个项目。
我的 elif 语句似乎适用于 IDLE 但不适用于 VSC
为了演示,我有一个非常简单的 if 语句:
dud = 'You'
if dud == 'You':
print('You got the dud!')
elif dud == 'Me':
print('ohhhh, I made myself sad')
else:
pass
当我将此代码提交给 IDLE 时,它没有问题。 但是,当我将完全相同的代码复制粘贴到 VSC 并在 Python 终端中运行时,出现以下错误:
PS C:\Users\William> & C:/Users/William/AppData/Local/Programs/Python/Python38-32/python.exe
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dud = 'You'
>>>
>>> if dud == 'you':
... print('You got the dud!')
...
>>> elif dud == 'Me':
File "<stdin>", line 1
elif dud == 'Me':
^
SyntaxError: invalid syntax
>>> print('ohhhh, I made myself sad')
File "<stdin>", line 1
print('ohhhh, I made myself sad')
^
IndentationError: unexpected indent
>>> else:
File "<stdin>", line 1
else:
^
SyntaxError: invalid syntax
>>> pass
File "<stdin>", line 1
pass
^
IndentationError: unexpected indent
>>>
当然,我尝试了各种不同类型的格式,但我无法让它工作。 如果我删除 elif 部分它工作正常,所以我觉得我必须缺少一些基本的东西。
任何帮助将不胜感激!
编辑:越来越奇怪的行为让我相信这在某种程度上是一个 Visual Studio 问题:
在“Python 交互式窗口”中运行代码 = 成功全新启动 VSC 并使用“在终端中运行 python 文件” = 成功“在终端中运行选择/行” = 在终端已运行后运行“在终端中运行 python 文件”时遇到上述错误= 上面遇到的错误
编辑:人们正确地指出,VSC 似乎在说要添加额外的行。 我不认为是这种情况:这是 VSC 中代码的屏幕截图
根据终端片段和屏幕截图,VSC 实际运行的内容相当于:
dud = 'You'
if dud == 'You':
print('You got the dud!')
elif dud == 'Me':
print('ohhhh, I made myself sad')
else:
pass
问题是print('You got the dud!')
之后的第二个换行符。 它让 Python 认为 if 语句已经全部完成,所以当它看到elif
和elif
所有内容时,它就会出错。
问题的根源尚不清楚。
注意...
>>> elif
你开始了一个新的语句并结束了 if 语句
elif <conditional>
本身是无效的,因此下面的每一行都被单独解释。
我建议使用 IPython 而不是常规的 Python REPL,或者使用 JupyterLab
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.