Python 语法基础

Python 执行方式

Python 代码可以通过两种主要方式执行:

1. 命令行交互式执行

python

>>> print("hello world")
hello world
>>>

2. 文件执行
创建扩展名为 .py 的文件,然后在命令行中运行:

bash

[root@www ~]# python3 test.py 
hello world

Python 缩进规则

缩进指的是代码行开头的空格。与其他编程语言不同,Python 中的缩进不仅影响代码可读性,更是语法的重要组成部分。

正确示例:

python

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

错误示例:

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!")

错误示例(不一致的缩进):

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

# 这是一个注释
print("Hello, World!")

行末注释:

python

print("Hello, World!")  # 这是一个注释

禁用代码执行:

python

# print("Hello, World!")
print("Cheers, Mate!")

多行注释

Python 没有专门的多行注释语法,但可以通过以下方式实现:

方法一:每行使用 #

python

# 这是一个注释
# 写在多行中
# 每行都需要井号
print("Hello, World!")

方法二:使用多行字符串

python

"""
这是一个注释
写在多行中
使用三引号
"""
print("Hello, World!")

python

'''
这也是一个多行注释
使用单引号三引号
'''
print("Hello, World!")

注意: 只要多行字符串没有被赋值给变量,Python 就会读取但忽略这些内容,从而实现多行注释的效果。

注释的最佳实践

  1. 代码解释: 用注释说明复杂的算法或逻辑

  2. 文档说明: 为函数、类和方法添加文档字符串

  3. 调试助手: 临时禁用代码段进行测试

  4. 可读性: 使代码更易于理解和维护

注释是编写高质量 Python 代码的重要工具,合理使用注释可以显著提高代码的可维护性和可读性。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐