[英]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.