我是一个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.exePython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32Type "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文件”上遇到的错误=上面遇到的错误
2 回答
白板的微信
TA贡献1883条经验 获得超3个赞
根据终端片段和屏幕截图,VSC 实际运行的内容等效于此:
dud = 'You'
if dud == 'You':
print('You got the dud!')
elif dud == 'Me':
print('ohhhh, I made myself sad')
else:
pass
问题是 在第二行换行符之后。这让Python认为if语句已经完成了,所以当它看到后面的所有内容时,它就会出错。print('You got the dud!')elif
但问题的根源尚不清楚。
饮歌长啸
TA贡献1951条经验 获得超3个赞
通知。。。
>>> elif
您已启动新语句并结束 if 语句
elif <conditional>它本身是无效的,因此后面的每一行都是自己解释的。
我建议使用IPython而不是常规的python REPL,或者使用JupyterLab。
添加回答
举报
0/150
提交
取消
