入门
Hello World 与注释
Python 使用 # 作为注释,使用三引号作为文档字符串。print() 函数支持 sep 和 end 参数来自定义输出格式。文档字符串作为文档可通过 help() 和 __doc__ 访问。
# This is a single-line comment
"""
This is a
multi-line comment (docstring)
"""
print("Hello, World!") # print to stdout
print("A", "B", "C", sep="-") # A-B-C
print("No newline", end="") # suppress newline缩进与代码块
与大多数语言不同,Python 使用缩进而非花括号来定义代码块。一致性至关重要——混合使用制表符和空格会导致 SyntaxError。PEP 8 建议每级使用 4 个空格。
# Python uses indentation (4 spaces) to define blocks
if True:
print("inside if")
if True:
print("nested block")
print("outside block")
# No braces! Indentation IS the syntax
def func():
x = 1
return x + 1输入与输出
input() 从标准输入读取字符串——需要数字时务必进行转换。使用 int()、float() 等进行转换。F-strings(Python 3.6+)是格式化字符串的首选方式。
# input() always returns a string
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # convert to int
print(f"Hello {name}, you are {age} years old")
# formatted output
print("Pi is approximately {:.2f}".format(3.14159))
print(f"{1000000:,}") # 1,000,000 with thousands separator多语句与行续接
使用分号分隔一行中的多个语句(在惯用 Python 中很少见)。长行可以用反斜杠续接,或在 ()、[]、{} 中自动续接。为提高可读性,优先使用隐式续接。
# multiple statements on one line (discouraged)
a = 1; b = 2; c = 3
# explicit line continuation
total = 1 + 2 + 3 + \
4 + 5 + 6
# implicit continuation inside brackets
nums = [
1, 2, 3,
4, 5, 6
]
result = (1 + 2
+ 3 + 4)Python 执行
Python 脚本使用 'python script.py' 运行。REPL 允许交互式实验。在 python 指向 Python 2 的系统上始终使用 python3。shebang 行使脚本在 Unix 上可执行。
# Run a script
# $ python script.py
# Run interactively (REPL)
# $ python
# >>> 2 + 2
# 4
# Shebang line for Unix scripts
#!/usr/bin/env python3
# Check Python version
import sys
print(sys.version)
print(sys.version_info.major) # 3变量与数据类型
变量与动态类型
Python 使用动态类型——变量可以在运行时改变类型。使用 type() 检查,isinstance() 验证。Python 3.6+ 支持类型提示(name: str = 'Alice')以获得 IDE 支持,但运行时不强制执行。
# Python is dynamically typed - no declaration needed
name = "Alice" # str
age = 30 # int
height = 5.7 # float
is_active = True # bool
items = [1, 2, 3] # list
# Type checking
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = 0 # chain assignment类型提示(Python 3.6+)
类型提示提高了代码可读性,并使 IDE 自动补全和使用 mypy 进行静态分析成为可能。它们在运行时不强制执行——Python 仍然是动态类型的。使用 Optional[X] 表示可能为 None 的值。
# Variable annotations
name: str = "Alice"
age: int = 30
scores: list[float] = [90.5, 85.0]
# Function annotations
def greet(name: str, times: int = 1) -> str:
return (f"Hi {name}! " * times).strip()
# Optional and Union
from typing import Optional, Union
def find(id: int) -> Optional[str]:
return "Alice" if id == 1 else None
# mypy for static type checking
# $ mypy script.py类型转换
Python 有内置转换函数:int()、float()、str()、bool()、list()、tuple()、set()、dict()。假值包括 0、''、[]、{}、None、False。int() 向零截断,而 round() 使用银行家舍入法。
# String to number
num_str = str(42) # "42"
num = int("42") # 42
float_num = float("3.14") # 3.14
# Number conversions
print(int(3.99)) # 3 (truncates toward zero)
print(int(-3.99)) # -3
print(round(3.14159, 2)) # 3.14
# Boolean conversion
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool("anything")) # True
# Collection conversions
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(set([1, 1, 2])) # {1, 2}数值类型
Python 整数具有任意精度(无溢出)。浮点数是 IEEE 754 双精度,存在常见的精度问题。复数是内置的。布尔值是 int 的子类(True==1,False==0)。在数字字面量中使用下划线以提高可读性。
# Integers (arbitrary precision)
big = 10 ** 100 # no overflow
print(type(big)) # <class 'int'>
# Floats (IEEE 754 double)
pi = 3.14159
print(0.1 + 0.2) # 0.30000000000000004
# Complex numbers
z = 3 + 4j
print(z.real, z.imag) # 3.0 4.0
print(abs(z)) # 5.0
# Boolean is subclass of int
print(isinstance(True, int)) # True
print(True + True) # 2
# Underscores in numbers (3.6+)
million = 1_000_000
binary = 0b_1010_1010常量与命名约定
Python 没有 const 关键字——ALL_CAPS 名称仅按约定作为常量(没有任何机制阻止重新赋值)。PEP 8 定义了命名规则:变量/函数使用 snake_case,类使用 PascalCase,常量使用 ALL_CAPS。前导下划线按约定表示“私有”;双下划线触发名称改写。
# Python has no true constants - convention only
MAX_SIZE = 100 # ALL_CAPS for constants
PI = 3.14159
# Naming conventions (PEP 8)
variable_name = "snake_case" # variables, functions
ClassName = "PascalCase" # classes
CONSTANT_VALUE = 100 # constants
_private_var = "underscore prefix" # private (convention)
__name_mangled = "double underscore" # name mangling
# dunder names (reserved)
__name__, __main__, __init__字符串
字符串方法
字符串是不可变的——方法返回新字符串。find() 在未找到时返回 -1,而 index() 抛出 ValueError。使用 isalpha()/isdigit()/isalnum() 进行验证。str 类有 40 多个方法——用 dir(str) 探索。
s = "Hello, World"
# Case operations
print(s.upper()) # HELLO, WORLD
print(s.lower()) # hello, world
print(s.title()) # Hello, World
print(s.capitalize()) # Hello, world
print(s.swapcase()) # hELLO, wORLD
# Search & replace
print(s.find("World")) # 7 (index, -1 if not found)
print(s.index("World")) # 7 (raises ValueError if not found)
print(s.replace("o", "0")) # Hell0, W0rld
print(s.count("l")) # 3
# Validation
print("abc".isalpha()) # True
print("123".isdigit()) # True
print(" ".isspace()) # True