Skip to content

Python 基本语法

Python 的语法与 Perl, C, Java 等语言有相似之处,但它也有独特的特性,特别是使用缩进来组织代码结构。

我们来探索一下在不同模式下执行 Python 代码。

不带脚本文件直接运行 python 命令(或 python3,取决于你的系统)会启动交互式解释器 (Read-Eval-Print Loop,读取-求值-输出循环):

Terminal window
$ python3
Python 3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

你可以在 >>> 提示符后直接输入 Python 命令,然后按 Enter 键查看结果:

>>> print("Hello, Python!")
Hello, Python!
>>> 2 + 3
5
>>>

注意:现代 Python (Python 3) 要求 print 函数使用括号:print(...)。

你可以将 Python 代码写入文件(通常使用 .py 扩展名),然后使用解释器执行它。

创建一个名为 hello.py 的文件,内容如下:

hello.py
print("Hello from the script!")
message = "Python is fun"
print(message)

在你的终端中运行这个脚本:

Terminal window
$ python3 hello.py

这将产生以下输出:

Hello from the script!
Python is fun

在 Linux/macOS 上,你可以让脚本直接可执行:

在 hello.py 文件的最顶部添加一个 ‘shebang’ 行来指定解释器:

hello.py
#!/usr/bin/env python3
print("Hello from the executable script!")
message = "Python is versatile"
print(message)

使文件可执行并运行它:

Terminal window
$ chmod +x hello.py
$ ./hello.py

这将产生:

Hello from the executable script!
Python is versatile

标识符是用于命名变量、函数、类、模块等的名称。规则如下:

不允许使用像 @, $, % 这样的标点符号。

命名约定 (PEP 8 风格指南):

这些词在 Python 中具有特殊含义,不能用作标识符。所有关键字都是小写的(除了 True、False 和 None)。

| False | await | else | import | pass | | None | break | except | in | raise | | True | class | finally | is | return | | and | continue | for | lambda | try | | as | def | from | nonlocal | while | | assert | del | global | not | with | | async | elif | if | or | yield |

Python 使用缩进(行开头的空白符)来定义代码块(或称 suite),而不是像许多其他语言那样使用花括号 {}。这是一项严格的要求。

标准且强烈推荐的缩进是每层 4 个空格。

weather = "sunny"
if weather == "sunny":
print("Wear sunglasses!") # Indented block for if statement
print("Enjoy the day!") # Same indentation level
else:
print("Bring an umbrella.") # Indented block for else statement
print("Have a good day regardless.") # Back to the outer indentation level

不正确的缩进会导致 IndentationError:

# Incorrect indentation - raises IndentationError
if True:
print("Answer")
print("True") # Error: unindent does not match any outer indentation level

语句通常以换行符结束。你可以使用行继续符 (\) 将语句延续到下一行:

total = 10 + \
20 + \
30
print(total) # Output: 60

在括号 ()、方括号 [] 和花括号 {} 内部,允许隐式地进行行继续:

weekdays = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
options = {
'color': 'blue',
'size': 'large',
'quantity': 5
}
result = (1 + 2 + 3 +
4 + 5 + 6)

Python 使用单引号 (')、双引号 (") 和三引号 (''' 或 """) 来表示字符串字面量。单引号和双引号功能相同。三引号允许字符串跨多行,常用于文档字符串 (docstrings)。

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
It is made up of multiple lines
and sentences.
"""
alt_paragraph = '''Another way
to write multi-line
strings.'''
print(word)
print(sentence)
print(paragraph)

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

# This is a full-line comment
print("Hello, World!") # This is an inline comment
# Use comments to explain code or disable lines temporarily
# print("This line won't execute")
# Multi-line comments are typically done
# using multiple single-line comments.

空行(只包含空白符或注释)会被 Python 忽略。它们用于通过分隔逻辑块来提高代码可读性。

内置的 input() 函数会暂停程序执行,等待用户输入内容并按 Enter 键。它总是将用户的输入作为字符串返回。

name = input("Please enter your name: ")
print(f"Hello, {name}!")
# If you need a number, convert the input string
age_str = input("Enter your age: ")
try:
age = int(age_str)
print(f"You will be {age + 1} next year.")
except ValueError:
print("Invalid age entered. Please enter a number.")
# Simple pause prompt (Python 2 used raw_input)
input("\nPress Enter key to exit.")

你可以用分号 (;) 分隔,将多个语句放在同一行上。尽管这是有效的语法,但风格指南 (如 PEP 8) 通常不推荐这样做,因为它会降低可读性。

x = 5; y = 10; print(x + y) # Less readable

构成代码块的一组语句被称为一个 suite。复合语句如 if、while、def、class 由一个以冒号 (;) 结尾的头部行和紧随其后的缩进 suite 组成。

# Example structure
if expression:
# Suite for the if block
statement1
statement2
elif another_expression:
# Suite for the elif block
statement3
else:
# Suite for the else block
statement4

Python 脚本可以接收通过命令行传递的参数。这些参数可以通过 sys.argv 列表获取(你需要 import sys)。sys.argv[0] 是脚本本身的名称,后续元素是参数。

对于更强大的命令行参数解析,强烈推荐使用标准库中的 argparse 模块,而不是手动处理 sys.argv。

# 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 received: {sys.argv[1:]}")
else:
print("No arguments provided.")
# Run like: python3 args_test.py first_arg 123 --option