Skip to content

Python 3 - 基本语法

Python 的语法与 Perl、C 和 Java 等语言有一些相似之处,但也有其独特的特点,尤其是在代码结构上使用缩进。

你可以通过两种主要方式与 Python 互动:

通过在终端中输入 python 或 python3 来启动 Python 解释器。你会看到一个提示符(通常是 >>>),你可以在这里输入 Python 代码并立即看到结果。这通常被称为 REPL (Read-Evaluate-Print Loop)。

$ python3
Python 3.9.7 (...) [Clang 13.0.0 (...)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, Interactive Python!")
Hello, Interactive Python!
>>> 2 + 3
5
>>> exit() # or quit() or Ctrl-D to exit

注意:在 Python 3 中,print 是一个函数,需要使用圆括号 ()。Python 2 则将 print 作为一条语句。

将你的 Python 代码写入一个以 .py 为扩展名的文件(例如 hello.py)。然后,从终端使用解释器运行该文件。

创建 hello.py 文件,内容如下:

hello.py
print("Hello from a Python script!")

从终端运行它:

$ python3 hello.py
Hello from a Python script!

在 Linux/macOS 上,你可以使脚本直接可执行。在文件顶部添加指向解释器的 ‘shebang’ 行,然后使文件可执行,再运行它:

修改 hello.py 文件:

hello.py
#!/usr/bin/env python3
print("Hello from an executable Python script!")

从终端运行:

$ chmod +x hello.py # Make executable
$ ./hello.py # Run directly
Hello from an executable Python script!

(通常推荐使用 #!/usr/bin/env python3,因为它会在用户的环境路径中查找 python3 解释器,而不是硬编码 /usr/bin/python3。)

标识符是用于变量、函数、类、模块等的名称。

  • 必须以字母 (a-z, A-Z) 或下划线 (_) 开头。
  • 可以跟随零个或多个字母、下划线和数字 (0-9)。
  • 不能包含 @、$、% 等标点符号。
  • 区分大小写:myVariable 和 myvariable 是不同的。
  • 不能是保留关键字(参见下文)。

常见的命名规范 (遵循 PEP 8 风格指南):

  • 变量、函数、模块:lowercase_with_underscores (蛇形命名法 - snake_case)。
  • 类:CapitalizedWords (驼峰命名法 - CamelCase 或 PascalCase)。
  • 常量:ALL_CAPS_WITH_UNDERSCORES。
  • 私有标识符(约定):以单个下划线开头 (_private_var)。
  • 强私有(名字修饰):以双下划线开头 (__mangled_var)。
  • 特殊的语言定义名称:以双下划线开头和结尾 (__init__, __name__)。

这些词在 Python 中具有特殊含义,不能用作标识符。它们总是小写。

Falseawaitelseimport
Nonebreakexceptin
Trueclassfinallyis
andcontinueforlambda
asdeffromnonlocal
assertdelglobalnot
asyncelififor

Python 使用缩进(行首的空格)来定义代码块(suites),而不是像许多其他语言那样使用大括号 {}。这是 Python 的核心特性,并且严格执行。

标准约定 (PEP 8) 是每级缩进使用4个空格。同一块中的所有语句必须具有相同的缩进。

# Correct indentation
if True:
print("Inside the if block") # 4 spaces indent
x = 10 # Also 4 spaces
if x > 5:
print("Inside nested if") # 8 spaces indent
else:
print("Inside the else block") # 4 spaces indent
print("Outside all blocks") # No indent

不正确的缩进会导致 IndentationError:

# Incorrect indentation - Generates IndentationError
if True:
print("Answer is True")
print("This line has wrong indentation") # Error!

Python 语句通常在行尾结束。要将一条语句延续到下一行,你可以使用行继续符 \(反斜杠)。

total = 1 + \
2 + \
3
print(total) # Output: 6

圆括号 ()、方括号 [] 或大括号 {} 内的语句可以跨多行分割,而无需使用反斜杠。

days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
player_stats = {'name': 'Alice', 'score': 100,
'level': 5}

Python 接受单引号 ('...')、双引号 ("...") 和三重引号 ('''...''' 或 """...""") 来表示字符串字面量。

  • 单引号和双引号功能完全相同。选择一种并保持一致。
  • 三重引号允许字符串自然地跨多行,常用于 docstrings。
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
It spans multiple lines.
"""
paragraph_alt = '''Another multi-line
string using single triple quotes.'''
print(paragraph)

使用井号 (#) 来开始注释。从 # 到行尾的所有内容都会被解释器忽略。

# This is a full-line comment
name = "Alice" # This is an inline comment explaining the variable
# Comments are used to explain code or temporarily disable it
# print("This line won't execute")

Python 没有像 C/Java 中的 /* ... */ 那样的特定语法来表示多行块注释。要注释掉多行,请在每行前加上 #。

(未赋值给变量的三重引号字符串有时会被用作块注释,但它们在技术上是字符串字面量,会被忽略,除非它们是模块/函数/类中的第一条语句,在这种情况下它们会成为 docstrings。)

空行(只包含空白或注释)会被解释器忽略,但可用于分隔逻辑块以提高代码可读性。

你可以将多条语句放在一行,用分号 (;) 分隔。然而,风格指南 (PEP 8) 通常不推荐这样做,因为它会降低可读性。

x = 5; y = 10; print(x + y) # Works, but often less clear than separate lines

一组作为单元执行的语句被称为 suite 或 block。在 Python 中,suite 是通过跟在以冒号 (:) 结尾的语句(如 if, while, for, def, class)之后的缩进来定义的。

if x > 0:
# Start of the 'if' suite (indented)
print("x is positive")
y = x * 2
# End of the 'if' suite
elif x == 0:
# Start of the 'elif' suite
print("x is zero")
# End of the 'elif' suite
else:
# Start of the 'else' suite
print("x is negative")
# End of the 'else' suite
# This statement is outside the if/elif/else structure

Python 脚本可以接受从命令行传递的参数。在现代 Python 中处理这些参数的标准方法是使用标准库中的 argparse 模块。

一种更简单(但不够健壮)的方法是访问 sys.argv(在 import sys 之后)。sys.argv 是一个列表,其中第一个元素 (sys.argv[0]) 是脚本名,后续元素是传递的参数。

# Example using sys.argv (save as args_test.py)
import sys
print(f"Script name: {sys.argv[0]}")
if len(sys.argv) > 1:
print(f"Arguments passed: {sys.argv[1:]}")
else:
print("No arguments provided.")
# Run like: python3 args_test.py arg1 100 --option

(对于简单情况之外的任何需求,建议学习 argparse。)