basic Python if statement throw error IndentationError

huangapple go评论63阅读模式
英文:

basic Python if statement throw error IndentationError

问题

我开始在openclassroom学习Python,但无法让if/else条件正常工作。
我在Google上搜索了好几个小时,但没有找到解决我的问题的方法。

我尝试了一个非常简单的语句,像这样:

a = 1

if a == 1:
    print("1")
else:
    print("not 1")

命令输出:

C:\Users\david>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb  7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>>
>>> a
1
>>>
>>> if a == 1:
... print("a equal 1")
  File "<stdin>", line 2
    print("a equal 1")
    ^
IndentationError: expected an indented block after 'if' statement on line 1
>>>

我在PyCharm中尝试了完全相同的代码,它正常工作。但在命令行中由于某种原因不起作用。

英文:

I started to learn python on openclassroom and I can't get the if/else conditions to work.
I searched on google for several hours and I did not find a solution to my problem.

I tried to make a very simple statement like this:

a = 1

if a == 1:
    print(&quot;1&quot;)
else:
    print(&quot;not 1&quot;)


command output:

C:\Users\david&gt;python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb  7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
&gt;&gt;&gt; a = 1
&gt;&gt;&gt;
&gt;&gt;&gt; a
1
&gt;&gt;&gt;
&gt;&gt;&gt; if a == 1:
... print(&quot;a equal 1&quot;)
  File &quot;&lt;stdin&gt;&quot;, line 2
    print(&quot;a equal 1&quot;)
    ^
IndentationError: expected an indented block after &#39;if&#39; statement on line 1
&gt;&gt;&gt;

i tried the same exact code in pycharm and it is working. but it doesn't work in cmd for some reason

答案1

得分: 1

这是因为你在 cmd 中没有缩进属性。

>>> a = 1
>>> if a == 1:
...     print("a == 1")
a == 1

要在 cmd 中缩进,只需按下 tab 键,它将缩进。

英文:

That is because you aren't indenting property in cmd.

&gt;&gt;&gt; a = 1
&gt;&gt;&gt; if a == 1:
...     print(&quot;a == 1&quot;)
a == 1

To indent in cmd, simply press tab, and it will indent.

答案2

得分: 0

你可能会在Python中遇到一个"IndentationError",这是因为你的代码缩进不正确。然而,在你的情况下,在第1行的if语句之后没有缩进的代码块。

英文:

You may receive an "IndentationError" in Python when your code is not indented correctly. In your case, however, you do not have an indented block after your if statement on line 1.

huangapple
  • 本文由 发表于 2023年3月7日 05:10:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定