Python elif在IDLE中工作,但不在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文件”上遇到的错误=上面遇到的错误


撒科打诨
浏览 274回答 2
2回答

白板的微信

根据终端片段和屏幕截图,VSC 实际运行的内容等效于此:dud = 'You'if dud == 'You':&nbsp; &nbsp; print('You got the dud!')elif dud == 'Me':&nbsp; &nbsp; print('ohhhh, I made myself sad')else:&nbsp; &nbsp; pass问题是 在第二行换行符之后。这让Python认为if语句已经完成了,所以当它看到后面的所有内容时,它就会出错。print('You got the dud!')elif但问题的根源尚不清楚。

饮歌长啸

通知。。。&nbsp;>>>&nbsp;elif您已启动新语句并结束 if 语句elif <conditional>它本身是无效的,因此后面的每一行都是自己解释的。我建议使用IPython而不是常规的python REPL,或者使用JupyterLab。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python