【问题标题】:What is the difference between these Python codes? [duplicate]这些 Python 代码有什么区别? [复制]
【发布时间】:2019-06-19 05:37:26
【问题描述】:

代码 1:

if 5 > 2:
 print ("Five is greater than two!")

代码 2:

if 5 > 2:
print ("Five is greater than two!")

这些代码有什么区别?

代码 1 在打印功能之前有一个额外的空间,而代码 2 在print 之前没有空间,但是当我尝试运行代码 1 时:它显示“预期的缩进块”:

【问题讨论】:

  • 缩进很重要。
  • 同“Let's eat, grandma”和“Let's eat grandma”:语法不同。阅读文档中的indentation
  • Python 中需要缩进
  • 如果您在执行时弹出的任何代码行有任何缩进问题。因此,如果您将 code1 和 code2 放在同一个脚本中。会出现缩进问题

标签: python


【解决方案1】:

与 C 等语言使用特殊标记来定义块(即{})不同,Python 通过缩进定义块。在第二个 sn-p 中,print 语句在if 下没有正确缩进,导致一个空的if 块(这在 Python 中是非法的),然后是一个不相关的 print 语句。

【讨论】:

  • 说得好,解释得好:)
【解决方案2】:

你需要缩进!

即使是一个空格缩进也不是很好,最好是使用四个:

if 5 > 2:
    print ("Five is greater than two!")

相关:Python: using 4 spaces for indentation. Why?

【讨论】:

  • 你能解释一下缩进吗
  • @RahulDora 检查 Murenik 的解决方案
猜你喜欢
  • 2014-04-01
  • 1970-01-01
  • 2012-09-27
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多