【发布时间】:2020-06-13 15:13:39
【问题描述】:
我是 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文件=错误 上面遇到过
edit:人们正确地指出,VSC 似乎在说添加了额外的行。 我不认为是这样:这是 VSC 中代码的屏幕截图
【问题讨论】:
-
print('You got the dud!')之后有一个额外的换行符 - 这导致 python 终端结束 if 语句。所以你的elif出现语法错误。 -
我认为这是复制/粘贴问题。因此,尝试在 Visual Studio 中编辑代码,使用退格键并输入...
-
题外话,但输出在哪里?您应该会在第二个
...之后看到You got the dud!。 FWIWelse子句也无关紧要。顺便说一句,欢迎来到 Stack Overflow!查看tour 和How to Ask。 -
大家好! VSC代码在这里:imgur.com/a/FGxAKZD
-
如果你有一个
.py文件,你不要将它复制/粘贴到 Python 终端。您通过启动启动调试器或 python 解释器。请参阅 VSC 调试页面了解如何设置launch.json