当前位置:首页 > python教程 > python基础

Python 语法

  • python 入门

执行 python 语法

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

>>> print("hello, world!")
hello, world!

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

c:usersyour 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!")

运行实例

  • python 入门

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!