Python 语法

执行 Python 语法

正如我们在上一节中学习到的,可以直接在命令行中编写执行 Python 的语法:

>>> print("Hello, World!")
Hello, World!

或者通过在服务器上创建 python 文件,使用 .py 文件扩展名,并在命令行中运行它:

C:\Users\Your Name>python myfile.py

Python 缩进

缩进指的是代码行开头的空格。

在其他编程语言中,代码缩进仅出于可读性的考虑,而 Python 中的缩进非常重要。

Python 使用缩进来指示代码块。

实例

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

运行实例

如果省略缩进,Python 会出错:

实例

语法错误:

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

运行实例

空格数取决于程序员,但至少需要一个。

实例

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

运行实例

您必须在同一代码块中使用相同数量的空格,否则 Python 会出错:

实例

语法错误:

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

运行实例

Python 变量

在 Python 中,变量是在为其赋值时创建的:

实例

Python 中的变量:

x = 5
y = "Hello, World!"

运行实例

Python 没有声明变量的命令。

您将在 Python 变量 章节中学习有关变量的更多知识。

注释

Python 拥有对文档内代码进行注释的功能。

注释以 # 开头,Python 将其余部分作为注释呈现:

实例

Python 中的注释:

#This is a comment.
print("Hello, World!")

运行实例