Python零基础入门实战教程:从Hello World到文件处理-2

第2章:第一个Python程序与代码规范

章节介绍

当你决定开始学习Python时,最让人兴奋的莫过于亲手写出第一个能运行的程序。那种看到自己写的几行代码在屏幕上输出“Hello, World!”的成就感,是驱使我们继续深入探索的巨大动力。

但编程不仅仅是让计算机执行指令,它更是一种创造和沟通。你写的代码,未来可能会被自己重新阅读,也可能被其他开发者查看。一段清晰、规范的代码,就像一篇结构清晰、用词准确的文章,能让阅读和理解变得轻松愉快。反之,混乱的代码则会让人头疼不已,甚至过段时间连自己都看不懂当初写了什么。因此,在写下第一个程序的同时,了解并养成好的代码规范习惯,是为你的编程之路打下最坚实、最有益的基础。

让我们从最经典的起点开始。几乎所有的编程语言入门都会从这个简单的程序入手,Python也不例外。它就像一个友好的挥手,标志着旅程的开始。

<?php
function getFirstPythonExample(string $language = 'zh'): string
{
    $examples = [
        'en' => <<<'PYTHON'
# My first Python program
print("Hello, World!")

# Variable declaration
name = "Alice"
age = 25

# Print with variables
print(f"My name is {name} and I am {age} years old")

# Simple calculation
x = 10
y = 5
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
PYTHON,
        'zh' => <<<'PYTHON'
# 我的第一个Python程序
print("Hello, World!")

# 变量声明
name = "张三"
age = 25

# 打印带变量的内容
print(f"我的名字是{name},今年{age}岁")

# 简单计算
x = 10
y = 5
sum = x + y
print(f"{x}{y}的和是{sum}")
PYTHON,
        'es' => <<<'PYTHON'
# Mi primer programa en Python
print("¡Hola, Mundo!")

# Declaración de variables
name = "María"
age = 25

# Imprimir con variables
print(f"Mi nombre es {name} y tengo {age} años")

# Cálculo simple
x = 10
y = 5
sum = x + y
print(f"La suma de {x} y {y} es {sum}")
PYTHON,
    ];

    return $examples[$language] ?? $examples['zh'];
}

这个例子虽然简单,却包含了几个关键要素:我们使用了 print 这个内置“函数”来向屏幕输出信息,而用引号包裹的 Hello, Python! 是一段“字符串”,也就是我们希望计算机展示的文本。执行它,你就能立刻获得反馈。

现在,假设我们想写一个稍微复杂点的程序,比如让用户输入名字并打招呼。我们可能会匆匆写下这样一段代码:

name = input("Enter your name: ")
print(  "Hello,"+name+"!" )

它能运行吗?很可能可以。但它看起来舒服吗?空格忽多忽少,拼接字符串的方式也有更清晰的写法。这时,代码规范的作用就体现出来了。Python社区有一份广为接受的代码风格指南,叫做 PEP 8。它就像是Python世界的写作手册,规定了如何安排缩进、空格、命名等细节,让所有人的代码看起来风格一致。

我们可以了解一下PEP 8的主要精神:

<?php
function getCodingStandards(string $language = 'zh'): array
{
    $standards = [
        'zh' => [
            [
                'title' => '命名规范',
                'items' => [
                    '变量名:使用小写字母和下划线,如:student_name',
                    '函数名:使用小写字母和下划线,如:calculate_average',
                    '类名:使用驼峰命名法,如:StudentRecord',
                    '常量名:使用大写字母和下划线,如:MAX_LENGTH'
                ]
            ],
            [
                'title' => '缩进规范',
                'items' => [
                    '使用4个空格进行缩进,不要使用制表符',
                    '函数定义和类定义之间空两行',
                    '同一代码块内的语句应对齐'
                ]
            ],
            [
                'title' => '注释规范',
                'items' => [
                    '单行注释以#开头,后面跟一个空格',
                    '多行注释使用三个双引号或单引号',
                    '函数和类应该有文档字符串(docstring)',
                    '复杂的代码段应该有注释说明'
                ]
            ],
            [
                'title' => '导入规范',
                'items' => [
                    '导入语句应放在文件顶部',
                    '每个导入应该单独一行',
                    '先导入标准库,再导入第三方库,最后导入本地模块',
                    '避免使用from module import *'
                ]
            ],
            [
                'title' => '其他规范',
                'items' => [
                    '每行不超过79个字符',
                    '在运算符前后和逗号后加空格',
                    '使用有意义的变量名',
                    '避免使用全局变量'
                ]
            ]
        ],
        'en' => [
            [
                'title' => 'Naming Conventions',
                'items' => [
                    'Variables: lowercase with underscores, e.g., student_name',
                    'Functions: lowercase with underscores, e.g., calculate_average',
                    'Classes: CamelCase, e.g., StudentRecord',
                    'Constants: UPPERCASE with underscores, e.g., MAX_LENGTH'
                ]
            ],
            [
                'title' => 'Indentation',
                'items' => [
                    'Use 4 spaces per indentation level, not tabs',
                    'Put two blank lines between function and class definitions',
                    'Align statements within the same code block'
                ]
            ],
            [
                'title' => 'Comments',
                'items' => [
                    'Single-line comments start with # followed by a space',
                    'Multi-line comments use triple quotes',
                    'Functions and classes should have docstrings',
                    'Complex code sections should have explanatory comments'
                ]
            ],
            [
                'title' => 'Imports',
                'items' => [
                    'Import statements should be at the top of the file',
                    'Each import should be on a separate line',
                    'Import standard libraries first, then third-party, then local modules',
                    'Avoid from module import *'
                ]
            ],
            [
                'title' => 'Other Standards',
                'items' => [
                    'Limit lines to 79 characters',
                    'Add spaces around operators and after commas',
                    'Use meaningful variable names',
                    'Avoid global variables'
                ]
            ]
        ],
        'es' => [
            [
                'title' => 'Convenciones de Nombres',
                'items' => [
                    'Variables: minúsculas con guiones bajos, ej., nombre_estudiante',
                    'Funciones: minúsculas con guiones bajos, ej., calcular_promedio',
                    'Clases: CamelCase, ej., RegistroEstudiante',
                    'Constantes: MAYÚSCULAS con guiones bajos, ej., LONGITUD_MAXIMA'
                ]
            ],
            [
                'title' => 'Indentación',
                'items' => [
                    'Use 4 espacios por nivel de indentación, no tabs',
                    'Poner dos líneas en blanco entre definiciones de funciones y clases',
                    'Alinear declaraciones dentro del mismo bloque de código'
                ]
            ],
            [
                'title' => 'Comentarios',
                'items' => [
                    'Los comentarios de una línea comienzan con # seguido de un espacio',
                    'Comentarios multi-línea usan comillas triples',
                    'Funciones y clases deben tener docstrings',
                    'Secciones de código complejas deben tener comentarios explicativos'
                ]
            ],
            [
                'title' => 'Importaciones',
                'items' => [
                    'Las declaraciones de importación deben estar en la parte superior del archivo',
                    'Cada importación debe estar en una línea separada',
                    'Importar bibliotecas estándar primero, luego terceras partes, luego módulos locales',
                    'Evitar from módulo import *'
                ]
            ],
            [
                'title' => 'Otros Estándares',
                'items' => [
                    'Limitar líneas a 79 caracteres',
                    'Agregar espacios alrededor de operadores y después de comas',
                    'Usar nombres de variables significativos',
                    'Evitar variables globales'
                ]
            ]
        ]
    ];
    
    return $standards[$language] ?? $standards['zh'];
}

知道了规范,我们如何检查自己的代码呢?可以直接用工具来评估:

<?php
function checkPEP8Compliance(string $code): array
{
    $result = [
        'score' => 100, // 初始分数
        'violations' => [],
        'compliance_percentage' => 0
    ];
    
    $lines = explode("\n", $code);
    $violationCount = 0;
    $totalChecks = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1;
        $totalChecks += 5; // 每行检查5个项目
        
        // 1. 检查行长度(PEP8: 不超过79字符)
        if (strlen($line) > 79) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => sprintf('行长度 %d 字符超过PEP8建议的79字符', strlen($line))
            ];
        }
        
        // 2. 检查行尾空白
        if (preg_match('/\s+$/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'error',
                'message' => '行尾存在多余空白字符'
            ];
        }
        
        // 3. 检查运算符周围的空格
        if (preg_match('/[=+\-*\/<>!]=/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '建议在运算符周围添加空格以提高可读性'
            ];
        }
        
        // 4. 检查注释格式
        if (preg_match('/^[ \t]*#[a-zA-Z]/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '注释应以空格开始,例如:# 注释内容'
            ];
        }
        
        // 5. 检查导入语句位置(简化检查)
        if (strpos($line, 'import ') !== false && $lineNumber > 10) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => '导入语句应位于文件顶部'
            ];
        }
    }
    
    // 计算合规率
    if ($totalChecks > 0) {
        $complianceRate = (($totalChecks - $violationCount) / $totalChecks) * 100;
        $result['compliance_percentage'] = round($complianceRate, 1);
        $result['score'] = max(0, $complianceRate);
    }
    
    return $result;
}

工具会给出具体的建议,比如“在运算符两边加上空格”、“函数名应该用小写字母和下划线”等等。遵循这些建议,我们把代码改进一下:

name = input("Enter your name: ")
print(f"Hello, {name}!")

看,使用了f-string进行格式化后,代码是不是立刻清晰多了?这就是规范带来的直观好处。

在动手编写时,两个工具非常实用。一个是代码验证,在你运行前帮你抓住明显的语法错误:

<?php
function validatePythonCode(string $code): array
{
    $result = [
        'is_valid' => true,
        'errors' => [],
        'warnings' => [],
        'suggestions' => []
    ];

    // 检查代码是否为空
    if (empty(trim($code))) {
        $result['is_valid'] = false;
        $result['errors'][] = '代码不能为空';
        return $result;
    }

    // 检查是否有print语句(基础要求)
    if (!str_contains($code, 'print')) {
        $result['warnings'][] = '代码中未发现print语句,建议添加输出语句以便看到结果';
    }

    // 检查缩进是否一致(基础检查)
    $lines = explode("\n", $code);
    $indentationTypes = [];
    $previousIndentLength = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1; //1开始计数
        
        // 跳过空行
        if (strlen(trim($line)) === 0) {
            continue;
        }
        
        // 检查行首空格缩进
        preg_match('/^(\s*)/', $line, $matches);
        $indent = $matches[1] ?? '';
        
        // 检查缩进类型(空格或制表符)
        if (str_contains($indent, ' ') && str_contains($indent, "\t")) {
            $result['errors'][] = "第{$lineNumber}行: 混合使用了空格和制表符进行缩进";
            $result['is_valid'] = false;
        } elseif (str_contains($indent, ' ')) {
            $indentationTypes['space'] = true;
        } elseif (str_contains($indent, "\t")) {
            $indentationTypes['tab'] = true;
        }
        
        // 检查缩进长度
        $indentLength = strlen($indent);
        if ($indentLength > 0 && $indentLength % 4 !== 0) {
            $result['warnings'][] = "第{$lineNumber}行: 缩进使用了{$indentLength}个字符,建议使用4个空格进行缩进";
        }
        
        // 检查缩进是否合理(对比上一行)
        if ($lineNumber > 1) {
            $diff = $indentLength - $previousIndentLength;
            if ($diff > 4) {
                $result['warnings'][] = "第{$lineNumber}行: 缩进增加过多,建议一次只增加4个空格";
            }
        }
        
        $previousIndentLength = $indentLength;
    }
    
    // 检查是否混合使用了空格和制表符
    if (count($indentationTypes) > 1) {
        $result['errors'][] = "代码中混合使用了空格和制表符进行缩进,请统一使用一种缩进方式";
        $result['is_valid'] = false;
    }
    
    // 检查代码是否有明显语法错误(简单版)
    if (preg_match('/^(?:[\t ]*)(?:if|else|elif|for|while|def|class)\b/', $code, $matches) &&
        !preg_match('/:\s*$/', $code)) {
        $result['errors'][] = "控制流语句或函数定义缺少冒号(:)结尾";
        $result['is_valid'] = false;
    }
    
    // 检查括号是否匹配
    $stack = [];
    $pairs = [
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '"' => '"',
        "'" => "'"
    ];
    
    for ($i = 0; $i < strlen($code); $i++) {
        $char = $code[$i];
        
        // 处理字符串字面量,跳过其中的括号
        if ($char === '"' || $char === "'") {
            if (empty($stack) || end($stack) !== $char) {
                $stack[] = $char;
            } else {
                array_pop($stack);
            }
            continue;
        }
        
        // 如果在字符串中,跳过括号检查
        if (!empty($stack) && (end($stack) === '"' || end($stack) === "'")) {
            continue;
        }
        
        // 处理括号
        if (in_array($char, ['(', '[', '{'])) {
            $stack[] = $char;
        } elseif (in_array($char, [')', ']', '}'])) {
            $last = array_pop($stack);
            if ($last === null || $pairs[$last] !== $char) {
                $result['errors'][] = "括号不匹配: 第" . ($i + 1) . "个字符'{$char}'没有对应的开括号";
                $result['is_valid'] = false;
            }
        }
    }
    
    // 检查未关闭的括号
    if (!empty($stack)) {
        foreach ($stack as $bracket) {
            $result['errors'][] = "未关闭的括号: '{$bracket}'";
        }
        $result['is_valid'] = false;
    }
    
    // 检查常见的拼写错误
    $commonMistakes = [
        'prnt' => 'print',
        'def ' => 'def ',
        'class ' => 'class ',
        'whlie' => 'while',
        'for ' => 'for ',
        'if ' => 'if ',
        'else:' => 'else:'
    ];
    
    foreach ($commonMistakes as $wrong => $correct) {
        if (preg_match('/\b' . preg_quote($wrong, '/') . '\b/', $code) && 
            !str_contains($code, $correct)) {
            $result['suggestions'][] = "可能拼写错误: '{$wrong}',应该是'{$correct}'吗?";
        }
    }
    
    // 如果代码有效,添加一个积极的建议
    if ($result['is_valid'] && empty($result['errors'])) {
        $result['suggestions'][] = '代码基本语法正确,可以考虑添加注释或优化代码结构';
    }

    return $result;
}

另一个是代码格式化,它可以自动调整缩进、空行,让你的代码布局整洁美观:

<?php
function formatPythonCode(string $code, int $indentSize = 4): string
{
    // 移除首尾空白
    $code = trim($code);
    
    // 标准化换行符
    $code = str_replace(["\r\n", "\r"], "\n", $code);
    
    $lines = explode("\n", $code);
    $formattedLines = [];
    $currentIndent = 0;
    
    foreach ($lines as $line) {
        $trimmedLine = ltrim($line);
        
        // 跳过空行,但保留逻辑块之间的空行
        if (empty($trimmedLine)) {
            if (!empty(end($formattedLines))) {
                $formattedLines[] = '';
            }
            continue;
        }
        
        // 计算新的缩进级别
        $originalIndent = strlen($line) - strlen($trimmedLine);
        $indentLevel = (int)($originalIndent / $indentSize);
        
        // 应用新的缩进
        $newIndent = str_repeat(' ', $indentLevel * $indentSize);
        $formattedLines[] = $newIndent . $trimmedLine;
    }
    
    // 移除多余的空行(连续空行保留一个)
    $result = [];
    $previousEmpty = false;
    
    foreach ($formattedLines as $line) {
        if (empty($line)) {
            if (!$previousEmpty) {
                $result[] = '';
                $previousEmpty = true;
            }
        } else {
            $result[] = $line;
            $previousEmpty = false;
        }
    }
    
    // 确保最后一行不是空行
    while (!empty($result) && empty(end($result))) {
        array_pop($result);
    }
    
    return implode("\n", $result);
}

为了让教程中的代码示例更清晰易读,我们也可以为它们加上简单的色彩提示:

<?php
function highlightPythonSyntax(string $code): string
{
    // 定义语法高亮规则
    $patterns = [
        // 关键字
        '/\b(def|class|if|else|elif|for|while|try|except|finally|import|from|as|return|break|continue|pass|and|or|not|in|is|None|True|False)\b/' 
            => '<span class="keyword">$1</span>',
        
        // 字符串
        '/([\'"])(.*?)\1/' 
            => '<span class="string">$1$2$1</span>',
        
        // 注释
        '/#(.*)$/m' 
            => '<span class="comment">#$1</span>',
        
        // 函数调用
        '/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/' 
            => '<span class="function">$1</span>(',
        
        // 数字
        '/\b(\d+\.?\d*)\b/' 
            => '<span class="number">$1</span>',
        
        // 内置函数
        '/\b(print|input|len|str|int|float|type|range|list|dict|set|tuple)\b/' 
            => '<span class="builtin">$1</span>',
    ];
    
    // 应用所有规则
    $highlighted = $code;
    foreach ($patterns as $pattern => $replacement) {
        $highlighted = preg_replace($pattern, $replacement, $highlighted);
    }
    
    // 添加行号
    $lines = explode("\n", $highlighted);
    $numberedLines = [];
    
    foreach ($lines as $i => $line) {
        $lineNumber = $i + 1;
        $numberedLines[] = sprintf(
            '<div class="code-line"><span class="line-number">%3d</span> <span class="line-content">%s</span></div>',
            $lineNumber,
            $line
        );
    }
    
    // 包裹在代码块中
    $result = '<div class="python-code">' . implode("\n", $numberedLines) . '</div>';
    
    // 添加CSS样式
    $css = <<<'CSS'
<style>
.python-code {
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    line-height: 1.5;
    overflow-x: auto;
}
.code-line {
    white-space: pre;
    margin: 2px 0;
}
.line-number {
    color: #6c757d;
    user-select: none;
    margin-right: 15px;
    display: inline-block;
    width: 40px;
    text-align: right;
}
.keyword { color: #007bff; font-weight: bold; }
.string { color: #28a745; }
.comment { color: #6c757d; font-style: italic; }
.function { color: #e83e8c; }
.number { color: #fd7e14; }
.builtin { color: #17a2b8; }
</style>
CSS;
    
    return $css . $result;
}

随着你编写的程序越来越复杂,你还会开始关心代码的结构和质量。比如,一段代码是不是太难理解?函数是不是做了太多事情?

<?php
function analyzeCodeComplexity(string $code): array
{
    $analysis = [
        'metrics' => [
            'total_lines' => 0,
            'code_lines' => 0,
            'comment_lines' => 0,
            'blank_lines' => 0,
            'function_count' => 0,
            'average_function_length' => 0,
            'cyclomatic_complexity' => 0
        ],
        'functions' => [],
        'complexity_level' => 'low'
    ];
    
    // 将代码按行分割
    $lines = explode("\n", $code);
    $analysis['metrics']['total_lines'] = count($lines);
    
    $inMultilineComment = false; // 是否在多行注释中
    $currentFunction = null;     // 当前解析的函数信息
    $functionLines = 0;          // 当前函数的行数
    $functionComplexity = 1;     // 当前函数的圈复杂度(基础为1)
    
    foreach ($lines as $lineNumber => $line) {
        $trimmedLine = trim($line);
        $lineNumber++; //1开始
        
        // 检查空行
        if (empty($trimmedLine)) {
            $analysis['metrics']['blank_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理多行注释(Python的三引号注释)
        $hasMultiStart = strpos($trimmedLine, '"""') === 0 || strpos($trimmedLine, "'''") === 0;
        $hasMultiEnd = substr_count($trimmedLine, '"""') >= 2 || substr_count($trimmedLine, "'''") >= 2;
        
        // 多行注释开始
        if ($hasMultiStart && !$inMultilineComment) {
            $inMultilineComment = true;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 多行注释结束
        if ($hasMultiEnd && $inMultilineComment) {
            $inMultilineComment = false;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 在多行注释中
        if ($inMultilineComment) {
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 处理单行注释(以#开头)
        if (strpos($trimmedLine, '#') === 0) {
            $analysis['metrics']['comment_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理内联注释
        $inlineCommentPos = strpos($trimmedLine, '#');
        if ($inlineCommentPos !== false) {
            $analysis['metrics']['comment_lines']++;
            $trimmedLine = trim(substr($trimmedLine, 0, $inlineCommentPos));
            if (empty($trimmedLine)) {
                continue;
            }
        }
        
        // 识别函数定义(以def开头)
        if (strpos($trimmedLine, 'def ') === 0) {
            // 如果有正在统计的函数,先保存
            if ($currentFunction !== null) {
                $analysis['functions'][] = [
                    'name' => $currentFunction,
                    'lines' => $functionLines,
                    'complexity' => $functionComplexity
                ];
            }
            
            // 解析函数名
            preg_match('/def\s+(\w+)\s*\(/', $trimmedLine, $matches);
            $currentFunction = isset($matches[1]) ? $matches[1] : 'anonymous_function';
            $analysis['metrics']['function_count']++;
            $functionLines = 1; // 函数定义行
            $functionComplexity = 1; // 重置圈复杂度
            
            // 检查函数定义中是否有默认参数(会增加复杂度)
            if (strpos($trimmedLine, '=') !== false) {
                $functionComplexity++;
            }
        } 
        // 如果是代码行且不在函数中
        elseif ($currentFunction === null) {
            $analysis['metrics']['code_lines']++;
            
            // 检查控制流语句(增加整体复杂度)
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
        }
        // 函数内的代码行
        else {
            $functionLines++;
            $analysis['metrics']['code_lines']++;
            
            // 计算函数内的圈复杂度
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查三元运算符
            if (strpos($trimmedLine, ' if ') !== false && strpos($trimmedLine, ' else ') !== false) {
                $functionComplexity++;
            }
        }
    }
    
    // 处理最后一个函数
    if ($currentFunction !== null) {
        $analysis['functions'][] = [
            'name' => $currentFunction,
            'lines' => $functionLines,
            'complexity' => $functionComplexity
        ];
    }
    
    // 计算平均函数长度
    if ($analysis['metrics']['function_count'] > 0) {
        $totalFunctionLines = 0;
        foreach ($analysis['functions'] as $func) {
            $totalFunctionLines += $func['lines'];
        }
        $analysis['metrics']['average_function_length'] = 
            round($totalFunctionLines / $analysis['metrics']['function_count'], 2);
    }
    
    // 计算平均圈复杂度
    if (!empty($analysis['functions'])) {
        $totalComplexity = 0;
        foreach ($analysis['functions'] as $func) {
            $totalComplexity += $func['complexity'];
        }
        $analysis['metrics']['cyclomatic_complexity'] = 
            round($totalComplexity / count($analysis['functions']), 2);
    }
    
    // 确定复杂度级别
    $avgComplexity = $analysis['metrics']['cyclomatic_complexity'];
    if ($avgComplexity < 5) {
        $analysis['complexity_level'] = 'low';
    } elseif ($avgComplexity >= 5 && $avgComplexity < 10) {
        $analysis['complexity_level'] = 'medium';
    } else {
        $analysis['complexity_level'] = 'high';
    }
    
    return $analysis;
}

对于真正的起步,你可能会需要一个干净、标准的代码文件开头,而不是从完全空白开始。这里有一些模板可以帮助你快速搭建结构:

<?php
function generatePythonTemplate(string $type = 'basic'): string
{
    $templates = [
        'basic' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单Python程序模板
作者:你的名字
日期:{date}
"""

def main():
    """主函数"""
    # 在这里编写你的代码
    print("Hello, Python!")

if __name__ == "__main__":
    main()
PYTHON,
        'calculator' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单计算器模板
"""

def add(a, b):
    """加法函数"""
    return a + b

def subtract(a, b):
    """减法函数"""
    return a - b

def multiply(a, b):
    """乘法函数"""
    return a * b

def divide(a, b):
    """除法函数"""
    if b == 0:
        return "错误:除数不能为0"
    return a / b

def main():
    """主函数"""
    print("简单计算器")
    print("=" * 20)
    
    try:
        # 获取用户输入
        num1 = float(input("请输入第一个数字: "))
        num2 = float(input("请输入第二个数字: "))
        operation = input("请选择操作 (+, -, *, /): ")
        
        # 根据操作符执行相应的运算
        if operation == '+':
            result = add(num1, num2)
            print(f"{num1} + {num2} = {result}")
        elif operation == '-':
            result = subtract(num1, num2)
            print(f"{num1} - {num2} = {result}")
        elif operation == '*':
            result = multiply(num1, num2)
            print(f"{num1} * {num2} = {result}")
        elif operation == '/':
            result = divide(num1, num2)
            print(f"{num1} / {num2} = {result}")
        else:
            print("错误:无效的操作符")
    except ValueError:
        print("错误:请输入有效的数字")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    main()
PYTHON,
        'data_analysis' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据分析模板
"""

import pandas as pd
import numpy as np

def load_data(filepath):
    """加载数据"""
    try:
        data = pd.read_csv(filepath)
        print(f"成功加载数据,共 {len(data)} 行,{len(data.columns)} 列")
        return data
    except FileNotFoundError:
        print(f"错误:找不到文件 {filepath}")
        return None
    except Exception as e:
        print(f"加载数据时发生错误: {e}")
        return None

def analyze_data(data):
    """数据分析"""
    if data is None:
        return
    
    print("\n数据基本信息:")
    print(data.info())
    
    print("\n数据统计摘要:")
    print(data.describe())
    
    print("\n前5行数据:")
    print(data.head())

def main():
    """主函数"""
    print("数据分析程序")
    print("=" * 20)
    
    # 加载数据
    data = load_data("data.csv")
    
    if data is not None:
        # 数据分析
        analyze_data(data)
        
        # 数据清洗示例
        print("\n正在清理缺失值...")
        data_cleaned = data.dropna()
        print(f"清理后数据: {len(data_cleaned)} 行")

if __name__ == "__main__":
    main()
PYTHON
    ];
    
    // 如果请求的类型不存在,使用基础模板
    if (!isset($templates[$type])) {
        $type = 'basic';
    }
    
    // 获取当前日期
    $currentDate = date('Y-m-d');
    
    // 替换模板中的占位符
    $template = $templates[$type];
    $template = str_replace('{date}', $currentDate, $template);
    
    return $template;
}

那么,就从现在开始吧。打开你的编辑器或IDE,不仅仅是模仿着写出那个“Hello, World!”,更有意识地留意代码的格式。想一想:缩进对齐了吗?变量名是否简单明了?多出来的空格是否让代码看起来松散?养成这些习惯的初期或许需要一点刻意练习,但它很快就会变成你的本能。写出计算机能执行的代码只是第一步,写出人类也能轻松理解的代码,才是优秀的开始。

核心概念

当你第一次接触Python时,最直观的感受可能就是它的简洁。一个完整的程序,可以简单到只有一行。

这就是我们常说的“Hello, World!”程序,它的唯一目的是向世界问好,并确认你的编程环境工作正常。在Python中,实现它无比直接:

<?php
function getFirstPythonExample(string $language = 'zh'): string
{
    $examples = [
        'en' => <<<'PYTHON'
# My first Python program
print("Hello, World!")

# Variable declaration
name = "Alice"
age = 25

# Print with variables
print(f"My name is {name} and I am {age} years old")

# Simple calculation
x = 10
y = 5
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
PYTHON,
        'zh' => <<<'PYTHON'
# 我的第一个Python程序
print("Hello, World!")

# 变量声明
name = "张三"
age = 25

# 打印带变量的内容
print(f"我的名字是{name},今年{age}岁")

# 简单计算
x = 10
y = 5
sum = x + y
print(f"{x}{y}的和是{sum}")
PYTHON,
        'es' => <<<'PYTHON'
# Mi primer programa en Python
print("¡Hola, Mundo!")

# Declaración de variables
name = "María"
age = 25

# Imprimir con variables
print(f"Mi nombre es {name} y tengo {age} años")

# Cálculo simple
x = 10
y = 5
sum = x + y
print(f"La suma de {x} y {y} es {sum}")
PYTHON,
    ];

    return $examples[$language] ?? $examples['zh'];
}

看到了吗?仅仅使用 print 这个内置函数,加上一对括号和引号,我们就完成了一个程序。这行代码像一句魔法咒语,它将引号内的字符——我们称之为“字符串”——原样输出到屏幕上。执行它,你就能立刻获得反馈,这种即时性正是Python吸引初学者的重要原因之一。

程序能够运行,这只是一个开始。想象一下,如果你的代码像一间堆满杂物的房间,虽然东西都在,但你想找到一支笔都困难。代码也是如此,它不仅要写给计算机执行,更要写给人(包括未来的你)阅读和理解。这就是代码规范的意义。

为什么我们要关心代码长什么样?

<?php
function getCodingStandards(string $language = 'zh'): array
{
    $standards = [
        'zh' => [
            [
                'title' => '命名规范',
                'items' => [
                    '变量名:使用小写字母和下划线,如:student_name',
                    '函数名:使用小写字母和下划线,如:calculate_average',
                    '类名:使用驼峰命名法,如:StudentRecord',
                    '常量名:使用大写字母和下划线,如:MAX_LENGTH'
                ]
            ],
            [
                'title' => '缩进规范',
                'items' => [
                    '使用4个空格进行缩进,不要使用制表符',
                    '函数定义和类定义之间空两行',
                    '同一代码块内的语句应对齐'
                ]
            ],
            [
                'title' => '注释规范',
                'items' => [
                    '单行注释以#开头,后面跟一个空格',
                    '多行注释使用三个双引号或单引号',
                    '函数和类应该有文档字符串(docstring)',
                    '复杂的代码段应该有注释说明'
                ]
            ],
            [
                'title' => '导入规范',
                'items' => [
                    '导入语句应放在文件顶部',
                    '每个导入应该单独一行',
                    '先导入标准库,再导入第三方库,最后导入本地模块',
                    '避免使用from module import *'
                ]
            ],
            [
                'title' => '其他规范',
                'items' => [
                    '每行不超过79个字符',
                    '在运算符前后和逗号后加空格',
                    '使用有意义的变量名',
                    '避免使用全局变量'
                ]
            ]
        ],
        'en' => [
            [
                'title' => 'Naming Conventions',
                'items' => [
                    'Variables: lowercase with underscores, e.g., student_name',
                    'Functions: lowercase with underscores, e.g., calculate_average',
                    'Classes: CamelCase, e.g., StudentRecord',
                    'Constants: UPPERCASE with underscores, e.g., MAX_LENGTH'
                ]
            ],
            [
                'title' => 'Indentation',
                'items' => [
                    'Use 4 spaces per indentation level, not tabs',
                    'Put two blank lines between function and class definitions',
                    'Align statements within the same code block'
                ]
            ],
            [
                'title' => 'Comments',
                'items' => [
                    'Single-line comments start with # followed by a space',
                    'Multi-line comments use triple quotes',
                    'Functions and classes should have docstrings',
                    'Complex code sections should have explanatory comments'
                ]
            ],
            [
                'title' => 'Imports',
                'items' => [
                    'Import statements should be at the top of the file',
                    'Each import should be on a separate line',
                    'Import standard libraries first, then third-party, then local modules',
                    'Avoid from module import *'
                ]
            ],
            [
                'title' => 'Other Standards',
                'items' => [
                    'Limit lines to 79 characters',
                    'Add spaces around operators and after commas',
                    'Use meaningful variable names',
                    'Avoid global variables'
                ]
            ]
        ],
        'es' => [
            [
                'title' => 'Convenciones de Nombres',
                'items' => [
                    'Variables: minúsculas con guiones bajos, ej., nombre_estudiante',
                    'Funciones: minúsculas con guiones bajos, ej., calcular_promedio',
                    'Clases: CamelCase, ej., RegistroEstudiante',
                    'Constantes: MAYÚSCULAS con guiones bajos, ej., LONGITUD_MAXIMA'
                ]
            ],
            [
                'title' => 'Indentación',
                'items' => [
                    'Use 4 espacios por nivel de indentación, no tabs',
                    'Poner dos líneas en blanco entre definiciones de funciones y clases',
                    'Alinear declaraciones dentro del mismo bloque de código'
                ]
            ],
            [
                'title' => 'Comentarios',
                'items' => [
                    'Los comentarios de una línea comienzan con # seguido de un espacio',
                    'Comentarios multi-línea usan comillas triples',
                    'Funciones y clases deben tener docstrings',
                    'Secciones de código complejas deben tener comentarios explicativos'
                ]
            ],
            [
                'title' => 'Importaciones',
                'items' => [
                    'Las declaraciones de importación deben estar en la parte superior del archivo',
                    'Cada importación debe estar en una línea separada',
                    'Importar bibliotecas estándar primero, luego terceras partes, luego módulos locales',
                    'Evitar from módulo import *'
                ]
            ],
            [
                'title' => 'Otros Estándares',
                'items' => [
                    'Limitar líneas a 79 caracteres',
                    'Agregar espacios alrededor de operadores y después de comas',
                    'Usar nombres de variables significativos',
                    'Evitar variables globales'
                ]
            ]
        ]
    ];
    
    return $standards[$language] ?? $standards['zh'];
}

这份指南会详细告诉你,统一的规范如何提升代码的可读性、可维护性,并减少错误。一个简单的例子:Python使用缩进来定义代码块,而不是像其他语言那样用花括号 {}。这意味着,随意的空格和缩进会导致程序逻辑完全错误。规范的缩进是Python语法的强制要求,也是清晰结构的体现。

你觉得下面两段代码,哪一段更容易阅读?

# 片段A
def calculate_sum(a,b):
    result=0
    for i in range(a,b+1):
        result+=i
    return result
# 片段B
def calculate_sum(start, end):
    total = 0
    for number in range(start, end + 1):
        total += number
    return total

显然,片段B更好。它使用了有意义的变量名,在操作符两边加了空格,看起来更舒展、更清晰。这些看似微小的细节,在项目代码量增长时会带来巨大的可读性差异。我们可以用工具来检查和改进代码规范。比如,你可以先用

<?php
function validatePythonCode(string $code): array
{
    $result = [
        'is_valid' => true,
        'errors' => [],
        'warnings' => [],
        'suggestions' => []
    ];

    // 检查代码是否为空
    if (empty(trim($code))) {
        $result['is_valid'] = false;
        $result['errors'][] = '代码不能为空';
        return $result;
    }

    // 检查是否有print语句(基础要求)
    if (!str_contains($code, 'print')) {
        $result['warnings'][] = '代码中未发现print语句,建议添加输出语句以便看到结果';
    }

    // 检查缩进是否一致(基础检查)
    $lines = explode("\n", $code);
    $indentationTypes = [];
    $previousIndentLength = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1; //1开始计数
        
        // 跳过空行
        if (strlen(trim($line)) === 0) {
            continue;
        }
        
        // 检查行首空格缩进
        preg_match('/^(\s*)/', $line, $matches);
        $indent = $matches[1] ?? '';
        
        // 检查缩进类型(空格或制表符)
        if (str_contains($indent, ' ') && str_contains($indent, "\t")) {
            $result['errors'][] = "第{$lineNumber}行: 混合使用了空格和制表符进行缩进";
            $result['is_valid'] = false;
        } elseif (str_contains($indent, ' ')) {
            $indentationTypes['space'] = true;
        } elseif (str_contains($indent, "\t")) {
            $indentationTypes['tab'] = true;
        }
        
        // 检查缩进长度
        $indentLength = strlen($indent);
        if ($indentLength > 0 && $indentLength % 4 !== 0) {
            $result['warnings'][] = "第{$lineNumber}行: 缩进使用了{$indentLength}个字符,建议使用4个空格进行缩进";
        }
        
        // 检查缩进是否合理(对比上一行)
        if ($lineNumber > 1) {
            $diff = $indentLength - $previousIndentLength;
            if ($diff > 4) {
                $result['warnings'][] = "第{$lineNumber}行: 缩进增加过多,建议一次只增加4个空格";
            }
        }
        
        $previousIndentLength = $indentLength;
    }
    
    // 检查是否混合使用了空格和制表符
    if (count($indentationTypes) > 1) {
        $result['errors'][] = "代码中混合使用了空格和制表符进行缩进,请统一使用一种缩进方式";
        $result['is_valid'] = false;
    }
    
    // 检查代码是否有明显语法错误(简单版)
    if (preg_match('/^(?:[\t ]*)(?:if|else|elif|for|while|def|class)\b/', $code, $matches) &&
        !preg_match('/:\s*$/', $code)) {
        $result['errors'][] = "控制流语句或函数定义缺少冒号(:)结尾";
        $result['is_valid'] = false;
    }
    
    // 检查括号是否匹配
    $stack = [];
    $pairs = [
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '"' => '"',
        "'" => "'"
    ];
    
    for ($i = 0; $i < strlen($code); $i++) {
        $char = $code[$i];
        
        // 处理字符串字面量,跳过其中的括号
        if ($char === '"' || $char === "'") {
            if (empty($stack) || end($stack) !== $char) {
                $stack[] = $char;
            } else {
                array_pop($stack);
            }
            continue;
        }
        
        // 如果在字符串中,跳过括号检查
        if (!empty($stack) && (end($stack) === '"' || end($stack) === "'")) {
            continue;
        }
        
        // 处理括号
        if (in_array($char, ['(', '[', '{'])) {
            $stack[] = $char;
        } elseif (in_array($char, [')', ']', '}'])) {
            $last = array_pop($stack);
            if ($last === null || $pairs[$last] !== $char) {
                $result['errors'][] = "括号不匹配: 第" . ($i + 1) . "个字符'{$char}'没有对应的开括号";
                $result['is_valid'] = false;
            }
        }
    }
    
    // 检查未关闭的括号
    if (!empty($stack)) {
        foreach ($stack as $bracket) {
            $result['errors'][] = "未关闭的括号: '{$bracket}'";
        }
        $result['is_valid'] = false;
    }
    
    // 检查常见的拼写错误
    $commonMistakes = [
        'prnt' => 'print',
        'def ' => 'def ',
        'class ' => 'class ',
        'whlie' => 'while',
        'for ' => 'for ',
        'if ' => 'if ',
        'else:' => 'else:'
    ];
    
    foreach ($commonMistakes as $wrong => $correct) {
        if (preg_match('/\b' . preg_quote($wrong, '/') . '\b/', $code) && 
            !str_contains($code, $correct)) {
            $result['suggestions'][] = "可能拼写错误: '{$wrong}',应该是'{$correct}'吗?";
        }
    }
    
    // 如果代码有效,添加一个积极的建议
    if ($result['is_valid'] && empty($result['errors'])) {
        $result['suggestions'][] = '代码基本语法正确,可以考虑添加注释或优化代码结构';
    }

    return $result;
}

检查基本语法,再用

<?php
function checkPEP8Compliance(string $code): array
{
    $result = [
        'score' => 100, // 初始分数
        'violations' => [],
        'compliance_percentage' => 0
    ];
    
    $lines = explode("\n", $code);
    $violationCount = 0;
    $totalChecks = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1;
        $totalChecks += 5; // 每行检查5个项目
        
        // 1. 检查行长度(PEP8: 不超过79字符)
        if (strlen($line) > 79) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => sprintf('行长度 %d 字符超过PEP8建议的79字符', strlen($line))
            ];
        }
        
        // 2. 检查行尾空白
        if (preg_match('/\s+$/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'error',
                'message' => '行尾存在多余空白字符'
            ];
        }
        
        // 3. 检查运算符周围的空格
        if (preg_match('/[=+\-*\/<>!]=/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '建议在运算符周围添加空格以提高可读性'
            ];
        }
        
        // 4. 检查注释格式
        if (preg_match('/^[ \t]*#[a-zA-Z]/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '注释应以空格开始,例如:# 注释内容'
            ];
        }
        
        // 5. 检查导入语句位置(简化检查)
        if (strpos($line, 'import ') !== false && $lineNumber > 10) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => '导入语句应位于文件顶部'
            ];
        }
    }
    
    // 计算合规率
    if ($totalChecks > 0) {
        $complianceRate = (($totalChecks - $violationCount) / $totalChecks) * 100;
        $result['compliance_percentage'] = round($complianceRate, 1);
        $result['score'] = max(0, $complianceRate);
    }
    
    return $result;
}

来获取更详细的风格改进建议。

遵循规范不仅能让他人理解你的代码,也能帮助你自己。清晰的代码结构让你在几周或几个月后回头修改时,能快速理清思路。我们可以使用

<?php
function formatPythonCode(string $code, int $indentSize = 4): string
{
    // 移除首尾空白
    $code = trim($code);
    
    // 标准化换行符
    $code = str_replace(["\r\n", "\r"], "\n", $code);
    
    $lines = explode("\n", $code);
    $formattedLines = [];
    $currentIndent = 0;
    
    foreach ($lines as $line) {
        $trimmedLine = ltrim($line);
        
        // 跳过空行,但保留逻辑块之间的空行
        if (empty($trimmedLine)) {
            if (!empty(end($formattedLines))) {
                $formattedLines[] = '';
            }
            continue;
        }
        
        // 计算新的缩进级别
        $originalIndent = strlen($line) - strlen($trimmedLine);
        $indentLevel = (int)($originalIndent / $indentSize);
        
        // 应用新的缩进
        $newIndent = str_repeat(' ', $indentLevel * $indentSize);
        $formattedLines[] = $newIndent . $trimmedLine;
    }
    
    // 移除多余的空行(连续空行保留一个)
    $result = [];
    $previousEmpty = false;
    
    foreach ($formattedLines as $line) {
        if (empty($line)) {
            if (!$previousEmpty) {
                $result[] = '';
                $previousEmpty = true;
            }
        } else {
            $result[] = $line;
            $previousEmpty = false;
        }
    }
    
    // 确保最后一行不是空行
    while (!empty($result) && empty(end($result))) {
        array_pop($result);
    }
    
    return implode("\n", $result);
}

自动格式化代码,使其符合统一的缩进和空行标准。对于想深入研究自己代码结构的人,

<?php
function analyzeCodeComplexity(string $code): array
{
    $analysis = [
        'metrics' => [
            'total_lines' => 0,
            'code_lines' => 0,
            'comment_lines' => 0,
            'blank_lines' => 0,
            'function_count' => 0,
            'average_function_length' => 0,
            'cyclomatic_complexity' => 0
        ],
        'functions' => [],
        'complexity_level' => 'low'
    ];
    
    // 将代码按行分割
    $lines = explode("\n", $code);
    $analysis['metrics']['total_lines'] = count($lines);
    
    $inMultilineComment = false; // 是否在多行注释中
    $currentFunction = null;     // 当前解析的函数信息
    $functionLines = 0;          // 当前函数的行数
    $functionComplexity = 1;     // 当前函数的圈复杂度(基础为1)
    
    foreach ($lines as $lineNumber => $line) {
        $trimmedLine = trim($line);
        $lineNumber++; //1开始
        
        // 检查空行
        if (empty($trimmedLine)) {
            $analysis['metrics']['blank_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理多行注释(Python的三引号注释)
        $hasMultiStart = strpos($trimmedLine, '"""') === 0 || strpos($trimmedLine, "'''") === 0;
        $hasMultiEnd = substr_count($trimmedLine, '"""') >= 2 || substr_count($trimmedLine, "'''") >= 2;
        
        // 多行注释开始
        if ($hasMultiStart && !$inMultilineComment) {
            $inMultilineComment = true;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 多行注释结束
        if ($hasMultiEnd && $inMultilineComment) {
            $inMultilineComment = false;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 在多行注释中
        if ($inMultilineComment) {
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 处理单行注释(以#开头)
        if (strpos($trimmedLine, '#') === 0) {
            $analysis['metrics']['comment_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理内联注释
        $inlineCommentPos = strpos($trimmedLine, '#');
        if ($inlineCommentPos !== false) {
            $analysis['metrics']['comment_lines']++;
            $trimmedLine = trim(substr($trimmedLine, 0, $inlineCommentPos));
            if (empty($trimmedLine)) {
                continue;
            }
        }
        
        // 识别函数定义(以def开头)
        if (strpos($trimmedLine, 'def ') === 0) {
            // 如果有正在统计的函数,先保存
            if ($currentFunction !== null) {
                $analysis['functions'][] = [
                    'name' => $currentFunction,
                    'lines' => $functionLines,
                    'complexity' => $functionComplexity
                ];
            }
            
            // 解析函数名
            preg_match('/def\s+(\w+)\s*\(/', $trimmedLine, $matches);
            $currentFunction = isset($matches[1]) ? $matches[1] : 'anonymous_function';
            $analysis['metrics']['function_count']++;
            $functionLines = 1; // 函数定义行
            $functionComplexity = 1; // 重置圈复杂度
            
            // 检查函数定义中是否有默认参数(会增加复杂度)
            if (strpos($trimmedLine, '=') !== false) {
                $functionComplexity++;
            }
        } 
        // 如果是代码行且不在函数中
        elseif ($currentFunction === null) {
            $analysis['metrics']['code_lines']++;
            
            // 检查控制流语句(增加整体复杂度)
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
        }
        // 函数内的代码行
        else {
            $functionLines++;
            $analysis['metrics']['code_lines']++;
            
            // 计算函数内的圈复杂度
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查三元运算符
            if (strpos($trimmedLine, ' if ') !== false && strpos($trimmedLine, ' else ') !== false) {
                $functionComplexity++;
            }
        }
    }
    
    // 处理最后一个函数
    if ($currentFunction !== null) {
        $analysis['functions'][] = [
            'name' => $currentFunction,
            'lines' => $functionLines,
            'complexity' => $functionComplexity
        ];
    }
    
    // 计算平均函数长度
    if ($analysis['metrics']['function_count'] > 0) {
        $totalFunctionLines = 0;
        foreach ($analysis['functions'] as $func) {
            $totalFunctionLines += $func['lines'];
        }
        $analysis['metrics']['average_function_length'] = 
            round($totalFunctionLines / $analysis['metrics']['function_count'], 2);
    }
    
    // 计算平均圈复杂度
    if (!empty($analysis['functions'])) {
        $totalComplexity = 0;
        foreach ($analysis['functions'] as $func) {
            $totalComplexity += $func['complexity'];
        }
        $analysis['metrics']['cyclomatic_complexity'] = 
            round($totalComplexity / count($analysis['functions']), 2);
    }
    
    // 确定复杂度级别
    $avgComplexity = $analysis['metrics']['cyclomatic_complexity'];
    if ($avgComplexity < 5) {
        $analysis['complexity_level'] = 'low';
    } elseif ($avgComplexity >= 5 && $avgComplexity < 10) {
        $analysis['complexity_level'] = 'medium';
    } else {
        $analysis['complexity_level'] = 'high';
    }
    
    return $analysis;
}

能提供函数数量、圈复杂度等指标,帮你识别潜在的复杂模块。

在实际编写时,从规范的结构开始会事半功倍。

<?php
function generatePythonTemplate(string $type = 'basic'): string
{
    $templates = [
        'basic' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单Python程序模板
作者:你的名字
日期:{date}
"""

def main():
    """主函数"""
    # 在这里编写你的代码
    print("Hello, Python!")

if __name__ == "__main__":
    main()
PYTHON,
        'calculator' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单计算器模板
"""

def add(a, b):
    """加法函数"""
    return a + b

def subtract(a, b):
    """减法函数"""
    return a - b

def multiply(a, b):
    """乘法函数"""
    return a * b

def divide(a, b):
    """除法函数"""
    if b == 0:
        return "错误:除数不能为0"
    return a / b

def main():
    """主函数"""
    print("简单计算器")
    print("=" * 20)
    
    try:
        # 获取用户输入
        num1 = float(input("请输入第一个数字: "))
        num2 = float(input("请输入第二个数字: "))
        operation = input("请选择操作 (+, -, *, /): ")
        
        # 根据操作符执行相应的运算
        if operation == '+':
            result = add(num1, num2)
            print(f"{num1} + {num2} = {result}")
        elif operation == '-':
            result = subtract(num1, num2)
            print(f"{num1} - {num2} = {result}")
        elif operation == '*':
            result = multiply(num1, num2)
            print(f"{num1} * {num2} = {result}")
        elif operation == '/':
            result = divide(num1, num2)
            print(f"{num1} / {num2} = {result}")
        else:
            print("错误:无效的操作符")
    except ValueError:
        print("错误:请输入有效的数字")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    main()
PYTHON,
        'data_analysis' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据分析模板
"""

import pandas as pd
import numpy as np

def load_data(filepath):
    """加载数据"""
    try:
        data = pd.read_csv(filepath)
        print(f"成功加载数据,共 {len(data)} 行,{len(data.columns)} 列")
        return data
    except FileNotFoundError:
        print(f"错误:找不到文件 {filepath}")
        return None
    except Exception as e:
        print(f"加载数据时发生错误: {e}")
        return None

def analyze_data(data):
    """数据分析"""
    if data is None:
        return
    
    print("\n数据基本信息:")
    print(data.info())
    
    print("\n数据统计摘要:")
    print(data.describe())
    
    print("\n前5行数据:")
    print(data.head())

def main():
    """主函数"""
    print("数据分析程序")
    print("=" * 20)
    
    # 加载数据
    data = load_data("data.csv")
    
    if data is not None:
        # 数据分析
        analyze_data(data)
        
        # 数据清洗示例
        print("\n正在清理缺失值...")
        data_cleaned = data.dropna()
        print(f"清理后数据: {len(data_cleaned)} 行")

if __name__ == "__main__":
    main()
PYTHON
    ];
    
    // 如果请求的类型不存在,使用基础模板
    if (!isset($templates[$type])) {
        $type = 'basic';
    }
    
    // 获取当前日期
    $currentDate = date('Y-m-d');
    
    // 替换模板中的占位符
    $template = $templates[$type];
    $template = str_replace('{date}', $currentDate, $template);
    
    return $template;
}

能为你生成一个基础的程序模板。当你把代码分享给别人或在文档中展示时,

<?php
function highlightPythonSyntax(string $code): string
{
    // 定义语法高亮规则
    $patterns = [
        // 关键字
        '/\b(def|class|if|else|elif|for|while|try|except|finally|import|from|as|return|break|continue|pass|and|or|not|in|is|None|True|False)\b/' 
            => '<span class="keyword">$1</span>',
        
        // 字符串
        '/([\'"])(.*?)\1/' 
            => '<span class="string">$1$2$1</span>',
        
        // 注释
        '/#(.*)$/m' 
            => '<span class="comment">#$1</span>',
        
        // 函数调用
        '/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/' 
            => '<span class="function">$1</span>(',
        
        // 数字
        '/\b(\d+\.?\d*)\b/' 
            => '<span class="number">$1</span>',
        
        // 内置函数
        '/\b(print|input|len|str|int|float|type|range|list|dict|set|tuple)\b/' 
            => '<span class="builtin">$1</span>',
    ];
    
    // 应用所有规则
    $highlighted = $code;
    foreach ($patterns as $pattern => $replacement) {
        $highlighted = preg_replace($pattern, $replacement, $highlighted);
    }
    
    // 添加行号
    $lines = explode("\n", $highlighted);
    $numberedLines = [];
    
    foreach ($lines as $i => $line) {
        $lineNumber = $i + 1;
        $numberedLines[] = sprintf(
            '<div class="code-line"><span class="line-number">%3d</span> <span class="line-content">%s</span></div>',
            $lineNumber,
            $line
        );
    }
    
    // 包裹在代码块中
    $result = '<div class="python-code">' . implode("\n", $numberedLines) . '</div>';
    
    // 添加CSS样式
    $css = <<<'CSS'
<style>
.python-code {
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    line-height: 1.5;
    overflow-x: auto;
}
.code-line {
    white-space: pre;
    margin: 2px 0;
}
.line-number {
    color: #6c757d;
    user-select: none;
    margin-right: 15px;
    display: inline-block;
    width: 40px;
    text-align: right;
}
.keyword { color: #007bff; font-weight: bold; }
.string { color: #28a745; }
.comment { color: #6c757d; font-style: italic; }
.function { color: #e83e8c; }
.number { color: #fd7e14; }
.builtin { color: #17a2b8; }
</style>
CSS;
    
    return $css . $result;
}

可以为代码添加颜色,使其关键部分(如函数名、关键字、字符串)一目了然。

所以,第一个Python程序 print(“Hello, World!”) 不仅是一句问候,更是一个起点。从写下这一行开始,就带着“写出清晰、规范代码”的意识。良好的习惯在开始时最容易养成,并会让你未来的编程之路走得更加顺畅。

实践应用

当你看到屏幕上打印出“Hello, World!”时,意味着你的Python旅程正式开始了。这个简单的程序,就像学习游泳时第一次把头埋进水里,让你真切地感受到了水的存在和代码的运行。它不仅是入门仪式,更是一个验证——验证环境配置正确,验证你能够与Python解释器对话。

<?php
function getFirstPythonExample(string $language = 'zh'): string
{
    $examples = [
        'en' => <<<'PYTHON'
# My first Python program
print("Hello, World!")

# Variable declaration
name = "Alice"
age = 25

# Print with variables
print(f"My name is {name} and I am {age} years old")

# Simple calculation
x = 10
y = 5
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
PYTHON,
        'zh' => <<<'PYTHON'
# 我的第一个Python程序
print("Hello, World!")

# 变量声明
name = "张三"
age = 25

# 打印带变量的内容
print(f"我的名字是{name},今年{age}岁")

# 简单计算
x = 10
y = 5
sum = x + y
print(f"{x}{y}的和是{sum}")
PYTHON,
        'es' => <<<'PYTHON'
# Mi primer programa en Python
print("¡Hola, Mundo!")

# Declaración de variables
name = "María"
age = 25

# Imprimir con variables
print(f"Mi nombre es {name} y tengo {age} años")

# Cálculo simple
x = 10
y = 5
sum = x + y
print(f"La suma de {x} y {y} es {sum}")
PYTHON,
    ];

    return $examples[$language] ?? $examples['zh'];
}

尝试运行这段代码,你将看到结果。但编程不只是让代码跑起来,更要让它清晰、优雅、易于理解。你有没有想过,为什么同样功能的代码,有的看起来清晰,有的却难以阅读?这很大程度上取决于代码规范。

让我们来做一个对比。看看这段代码,虽然它能运行,但布局有些混乱:

def greet(name):
return f"Hello, {name}!"
print(greet("World"))

这时候,代码规范就派上用场了。我们可以使用一个工具来让它变得规整。通过

<?php
function formatPythonCode(string $code, int $indentSize = 4): string
{
    // 移除首尾空白
    $code = trim($code);
    
    // 标准化换行符
    $code = str_replace(["\r\n", "\r"], "\n", $code);
    
    $lines = explode("\n", $code);
    $formattedLines = [];
    $currentIndent = 0;
    
    foreach ($lines as $line) {
        $trimmedLine = ltrim($line);
        
        // 跳过空行,但保留逻辑块之间的空行
        if (empty($trimmedLine)) {
            if (!empty(end($formattedLines))) {
                $formattedLines[] = '';
            }
            continue;
        }
        
        // 计算新的缩进级别
        $originalIndent = strlen($line) - strlen($trimmedLine);
        $indentLevel = (int)($originalIndent / $indentSize);
        
        // 应用新的缩进
        $newIndent = str_repeat(' ', $indentLevel * $indentSize);
        $formattedLines[] = $newIndent . $trimmedLine;
    }
    
    // 移除多余的空行(连续空行保留一个)
    $result = [];
    $previousEmpty = false;
    
    foreach ($formattedLines as $line) {
        if (empty($line)) {
            if (!$previousEmpty) {
                $result[] = '';
                $previousEmpty = true;
            }
        } else {
            $result[] = $line;
            $previousEmpty = false;
        }
    }
    
    // 确保最后一行不是空行
    while (!empty($result) && empty(end($result))) {
        array_pop($result);
    }
    
    return implode("\n", $result);
}

,我们可以自动调整缩进和空行,让代码结构立刻清晰起来。格式化后的代码会遵循统一的缩进标准(通常是4个空格),这是Python语法的基石,直接决定了代码块的逻辑层次。

然而,格式化只是代码规范的表面。Python社区有一套被广泛认可的编码风格指南——PEP 8。它详细规定了命名、空格、注释等方方面面的细节。想知道你自己的代码离专业水准有多远吗?

<?php
function checkPEP8Compliance(string $code): array
{
    $result = [
        'score' => 100, // 初始分数
        'violations' => [],
        'compliance_percentage' => 0
    ];
    
    $lines = explode("\n", $code);
    $violationCount = 0;
    $totalChecks = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1;
        $totalChecks += 5; // 每行检查5个项目
        
        // 1. 检查行长度(PEP8: 不超过79字符)
        if (strlen($line) > 79) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => sprintf('行长度 %d 字符超过PEP8建议的79字符', strlen($line))
            ];
        }
        
        // 2. 检查行尾空白
        if (preg_match('/\s+$/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'error',
                'message' => '行尾存在多余空白字符'
            ];
        }
        
        // 3. 检查运算符周围的空格
        if (preg_match('/[=+\-*\/<>!]=/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '建议在运算符周围添加空格以提高可读性'
            ];
        }
        
        // 4. 检查注释格式
        if (preg_match('/^[ \t]*#[a-zA-Z]/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '注释应以空格开始,例如:# 注释内容'
            ];
        }
        
        // 5. 检查导入语句位置(简化检查)
        if (strpos($line, 'import ') !== false && $lineNumber > 10) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => '导入语句应位于文件顶部'
            ];
        }
    }
    
    // 计算合规率
    if ($totalChecks > 0) {
        $complianceRate = (($totalChecks - $violationCount) / $totalChecks) * 100;
        $result['compliance_percentage'] = round($complianceRate, 1);
        $result['score'] = max(0, $complianceRate);
    }
    
    return $result;
}

这个检查会告诉你代码中哪些地方违反了PEP 8规范,并给出具体的改进建议。比如,它会提醒你函数名应该用小写字母和下划线,行长度最好不要超过79个字符等等。遵循这些规范,你的代码不仅能让自己看懂,更能让其他Python开发者轻松理解和协作。

实践是巩固知识的最好方式。除了打印一句话,我们还可以尝试写一个更实用的小程序。比如,一个简单的个人计算器,它能记录你的名字并问候你。

<?php
function generatePythonTemplate(string $type = 'basic'): string
{
    $templates = [
        'basic' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单Python程序模板
作者:你的名字
日期:{date}
"""

def main():
    """主函数"""
    # 在这里编写你的代码
    print("Hello, Python!")

if __name__ == "__main__":
    main()
PYTHON,
        'calculator' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单计算器模板
"""

def add(a, b):
    """加法函数"""
    return a + b

def subtract(a, b):
    """减法函数"""
    return a - b

def multiply(a, b):
    """乘法函数"""
    return a * b

def divide(a, b):
    """除法函数"""
    if b == 0:
        return "错误:除数不能为0"
    return a / b

def main():
    """主函数"""
    print("简单计算器")
    print("=" * 20)
    
    try:
        # 获取用户输入
        num1 = float(input("请输入第一个数字: "))
        num2 = float(input("请输入第二个数字: "))
        operation = input("请选择操作 (+, -, *, /): ")
        
        # 根据操作符执行相应的运算
        if operation == '+':
            result = add(num1, num2)
            print(f"{num1} + {num2} = {result}")
        elif operation == '-':
            result = subtract(num1, num2)
            print(f"{num1} - {num2} = {result}")
        elif operation == '*':
            result = multiply(num1, num2)
            print(f"{num1} * {num2} = {result}")
        elif operation == '/':
            result = divide(num1, num2)
            print(f"{num1} / {num2} = {result}")
        else:
            print("错误:无效的操作符")
    except ValueError:
        print("错误:请输入有效的数字")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    main()
PYTHON,
        'data_analysis' => <<<'PYTHON'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据分析模板
"""

import pandas as pd
import numpy as np

def load_data(filepath):
    """加载数据"""
    try:
        data = pd.read_csv(filepath)
        print(f"成功加载数据,共 {len(data)} 行,{len(data.columns)} 列")
        return data
    except FileNotFoundError:
        print(f"错误:找不到文件 {filepath}")
        return None
    except Exception as e:
        print(f"加载数据时发生错误: {e}")
        return None

def analyze_data(data):
    """数据分析"""
    if data is None:
        return
    
    print("\n数据基本信息:")
    print(data.info())
    
    print("\n数据统计摘要:")
    print(data.describe())
    
    print("\n前5行数据:")
    print(data.head())

def main():
    """主函数"""
    print("数据分析程序")
    print("=" * 20)
    
    # 加载数据
    data = load_data("data.csv")
    
    if data is not None:
        # 数据分析
        analyze_data(data)
        
        # 数据清洗示例
        print("\n正在清理缺失值...")
        data_cleaned = data.dropna()
        print(f"清理后数据: {len(data_cleaned)} 行")

if __name__ == "__main__":
    main()
PYTHON
    ];
    
    // 如果请求的类型不存在,使用基础模板
    if (!isset($templates[$type])) {
        $type = 'basic';
    }
    
    // 获取当前日期
    $currentDate = date('Y-m-d');
    
    // 替换模板中的占位符
    $template = $templates[$type];
    $template = str_replace('{date}', $currentDate, $template);
    
    return $template;
}

你可以使用上面这个基础模板作为起点,快速搭建起代码框架,然后填充你自己的逻辑。在编写过程中,随时可以

<?php
function validatePythonCode(string $code): array
{
    $result = [
        'is_valid' => true,
        'errors' => [],
        'warnings' => [],
        'suggestions' => []
    ];

    // 检查代码是否为空
    if (empty(trim($code))) {
        $result['is_valid'] = false;
        $result['errors'][] = '代码不能为空';
        return $result;
    }

    // 检查是否有print语句(基础要求)
    if (!str_contains($code, 'print')) {
        $result['warnings'][] = '代码中未发现print语句,建议添加输出语句以便看到结果';
    }

    // 检查缩进是否一致(基础检查)
    $lines = explode("\n", $code);
    $indentationTypes = [];
    $previousIndentLength = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1; //1开始计数
        
        // 跳过空行
        if (strlen(trim($line)) === 0) {
            continue;
        }
        
        // 检查行首空格缩进
        preg_match('/^(\s*)/', $line, $matches);
        $indent = $matches[1] ?? '';
        
        // 检查缩进类型(空格或制表符)
        if (str_contains($indent, ' ') && str_contains($indent, "\t")) {
            $result['errors'][] = "第{$lineNumber}行: 混合使用了空格和制表符进行缩进";
            $result['is_valid'] = false;
        } elseif (str_contains($indent, ' ')) {
            $indentationTypes['space'] = true;
        } elseif (str_contains($indent, "\t")) {
            $indentationTypes['tab'] = true;
        }
        
        // 检查缩进长度
        $indentLength = strlen($indent);
        if ($indentLength > 0 && $indentLength % 4 !== 0) {
            $result['warnings'][] = "第{$lineNumber}行: 缩进使用了{$indentLength}个字符,建议使用4个空格进行缩进";
        }
        
        // 检查缩进是否合理(对比上一行)
        if ($lineNumber > 1) {
            $diff = $indentLength - $previousIndentLength;
            if ($diff > 4) {
                $result['warnings'][] = "第{$lineNumber}行: 缩进增加过多,建议一次只增加4个空格";
            }
        }
        
        $previousIndentLength = $indentLength;
    }
    
    // 检查是否混合使用了空格和制表符
    if (count($indentationTypes) > 1) {
        $result['errors'][] = "代码中混合使用了空格和制表符进行缩进,请统一使用一种缩进方式";
        $result['is_valid'] = false;
    }
    
    // 检查代码是否有明显语法错误(简单版)
    if (preg_match('/^(?:[\t ]*)(?:if|else|elif|for|while|def|class)\b/', $code, $matches) &&
        !preg_match('/:\s*$/', $code)) {
        $result['errors'][] = "控制流语句或函数定义缺少冒号(:)结尾";
        $result['is_valid'] = false;
    }
    
    // 检查括号是否匹配
    $stack = [];
    $pairs = [
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '"' => '"',
        "'" => "'"
    ];
    
    for ($i = 0; $i < strlen($code); $i++) {
        $char = $code[$i];
        
        // 处理字符串字面量,跳过其中的括号
        if ($char === '"' || $char === "'") {
            if (empty($stack) || end($stack) !== $char) {
                $stack[] = $char;
            } else {
                array_pop($stack);
            }
            continue;
        }
        
        // 如果在字符串中,跳过括号检查
        if (!empty($stack) && (end($stack) === '"' || end($stack) === "'")) {
            continue;
        }
        
        // 处理括号
        if (in_array($char, ['(', '[', '{'])) {
            $stack[] = $char;
        } elseif (in_array($char, [')', ']', '}'])) {
            $last = array_pop($stack);
            if ($last === null || $pairs[$last] !== $char) {
                $result['errors'][] = "括号不匹配: 第" . ($i + 1) . "个字符'{$char}'没有对应的开括号";
                $result['is_valid'] = false;
            }
        }
    }
    
    // 检查未关闭的括号
    if (!empty($stack)) {
        foreach ($stack as $bracket) {
            $result['errors'][] = "未关闭的括号: '{$bracket}'";
        }
        $result['is_valid'] = false;
    }
    
    // 检查常见的拼写错误
    $commonMistakes = [
        'prnt' => 'print',
        'def ' => 'def ',
        'class ' => 'class ',
        'whlie' => 'while',
        'for ' => 'for ',
        'if ' => 'if ',
        'else:' => 'else:'
    ];
    
    foreach ($commonMistakes as $wrong => $correct) {
        if (preg_match('/\b' . preg_quote($wrong, '/') . '\b/', $code) && 
            !str_contains($code, $correct)) {
            $result['suggestions'][] = "可能拼写错误: '{$wrong}',应该是'{$correct}'吗?";
        }
    }
    
    // 如果代码有效,添加一个积极的建议
    if ($result['is_valid'] && empty($result['errors'])) {
        $result['suggestions'][] = '代码基本语法正确,可以考虑添加注释或优化代码结构';
    }

    return $result;
}

来确保你的语法正确无误,避免因拼写错误或缺少冒号这样的细节而卡住。

随着你编写更多代码,可能会关心它的质量。它复杂吗?容易维护吗?

<?php
function analyzeCodeComplexity(string $code): array
{
    $analysis = [
        'metrics' => [
            'total_lines' => 0,
            'code_lines' => 0,
            'comment_lines' => 0,
            'blank_lines' => 0,
            'function_count' => 0,
            'average_function_length' => 0,
            'cyclomatic_complexity' => 0
        ],
        'functions' => [],
        'complexity_level' => 'low'
    ];
    
    // 将代码按行分割
    $lines = explode("\n", $code);
    $analysis['metrics']['total_lines'] = count($lines);
    
    $inMultilineComment = false; // 是否在多行注释中
    $currentFunction = null;     // 当前解析的函数信息
    $functionLines = 0;          // 当前函数的行数
    $functionComplexity = 1;     // 当前函数的圈复杂度(基础为1)
    
    foreach ($lines as $lineNumber => $line) {
        $trimmedLine = trim($line);
        $lineNumber++; //1开始
        
        // 检查空行
        if (empty($trimmedLine)) {
            $analysis['metrics']['blank_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理多行注释(Python的三引号注释)
        $hasMultiStart = strpos($trimmedLine, '"""') === 0 || strpos($trimmedLine, "'''") === 0;
        $hasMultiEnd = substr_count($trimmedLine, '"""') >= 2 || substr_count($trimmedLine, "'''") >= 2;
        
        // 多行注释开始
        if ($hasMultiStart && !$inMultilineComment) {
            $inMultilineComment = true;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 多行注释结束
        if ($hasMultiEnd && $inMultilineComment) {
            $inMultilineComment = false;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 在多行注释中
        if ($inMultilineComment) {
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 处理单行注释(以#开头)
        if (strpos($trimmedLine, '#') === 0) {
            $analysis['metrics']['comment_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理内联注释
        $inlineCommentPos = strpos($trimmedLine, '#');
        if ($inlineCommentPos !== false) {
            $analysis['metrics']['comment_lines']++;
            $trimmedLine = trim(substr($trimmedLine, 0, $inlineCommentPos));
            if (empty($trimmedLine)) {
                continue;
            }
        }
        
        // 识别函数定义(以def开头)
        if (strpos($trimmedLine, 'def ') === 0) {
            // 如果有正在统计的函数,先保存
            if ($currentFunction !== null) {
                $analysis['functions'][] = [
                    'name' => $currentFunction,
                    'lines' => $functionLines,
                    'complexity' => $functionComplexity
                ];
            }
            
            // 解析函数名
            preg_match('/def\s+(\w+)\s*\(/', $trimmedLine, $matches);
            $currentFunction = isset($matches[1]) ? $matches[1] : 'anonymous_function';
            $analysis['metrics']['function_count']++;
            $functionLines = 1; // 函数定义行
            $functionComplexity = 1; // 重置圈复杂度
            
            // 检查函数定义中是否有默认参数(会增加复杂度)
            if (strpos($trimmedLine, '=') !== false) {
                $functionComplexity++;
            }
        } 
        // 如果是代码行且不在函数中
        elseif ($currentFunction === null) {
            $analysis['metrics']['code_lines']++;
            
            // 检查控制流语句(增加整体复杂度)
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
        }
        // 函数内的代码行
        else {
            $functionLines++;
            $analysis['metrics']['code_lines']++;
            
            // 计算函数内的圈复杂度
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查三元运算符
            if (strpos($trimmedLine, ' if ') !== false && strpos($trimmedLine, ' else ') !== false) {
                $functionComplexity++;
            }
        }
    }
    
    // 处理最后一个函数
    if ($currentFunction !== null) {
        $analysis['functions'][] = [
            'name' => $currentFunction,
            'lines' => $functionLines,
            'complexity' => $functionComplexity
        ];
    }
    
    // 计算平均函数长度
    if ($analysis['metrics']['function_count'] > 0) {
        $totalFunctionLines = 0;
        foreach ($analysis['functions'] as $func) {
            $totalFunctionLines += $func['lines'];
        }
        $analysis['metrics']['average_function_length'] = 
            round($totalFunctionLines / $analysis['metrics']['function_count'], 2);
    }
    
    // 计算平均圈复杂度
    if (!empty($analysis['functions'])) {
        $totalComplexity = 0;
        foreach ($analysis['functions'] as $func) {
            $totalComplexity += $func['complexity'];
        }
        $analysis['metrics']['cyclomatic_complexity'] = 
            round($totalComplexity / count($analysis['functions']), 2);
    }
    
    // 确定复杂度级别
    $avgComplexity = $analysis['metrics']['cyclomatic_complexity'];
    if ($avgComplexity < 5) {
        $analysis['complexity_level'] = 'low';
    } elseif ($avgComplexity >= 5 && $avgComplexity < 10) {
        $analysis['complexity_level'] = 'medium';
    } else {
        $analysis['complexity_level'] = 'high';
    }
    
    return $analysis;
}

这个分析会提供代码的行数、函数数量等基本指标,甚至计算圈复杂度,帮助你客观地评估代码的结构。复杂度低的代码通常意味着更容易测试和修改。

当你准备把代码分享给别人或在文档中展示时,让它看起来更美观总是加分项。

<?php
function highlightPythonSyntax(string $code): string
{
    // 定义语法高亮规则
    $patterns = [
        // 关键字
        '/\b(def|class|if|else|elif|for|while|try|except|finally|import|from|as|return|break|continue|pass|and|or|not|in|is|None|True|False)\b/' 
            => '<span class="keyword">$1</span>',
        
        // 字符串
        '/([\'"])(.*?)\1/' 
            => '<span class="string">$1$2$1</span>',
        
        // 注释
        '/#(.*)$/m' 
            => '<span class="comment">#$1</span>',
        
        // 函数调用
        '/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/' 
            => '<span class="function">$1</span>(',
        
        // 数字
        '/\b(\d+\.?\d*)\b/' 
            => '<span class="number">$1</span>',
        
        // 内置函数
        '/\b(print|input|len|str|int|float|type|range|list|dict|set|tuple)\b/' 
            => '<span class="builtin">$1</span>',
    ];
    
    // 应用所有规则
    $highlighted = $code;
    foreach ($patterns as $pattern => $replacement) {
        $highlighted = preg_replace($pattern, $replacement, $highlighted);
    }
    
    // 添加行号
    $lines = explode("\n", $highlighted);
    $numberedLines = [];
    
    foreach ($lines as $i => $line) {
        $lineNumber = $i + 1;
        $numberedLines[] = sprintf(
            '<div class="code-line"><span class="line-number">%3d</span> <span class="line-content">%s</span></div>',
            $lineNumber,
            $line
        );
    }
    
    // 包裹在代码块中
    $result = '<div class="python-code">' . implode("\n", $numberedLines) . '</div>';
    
    // 添加CSS样式
    $css = <<<'CSS'
<style>
.python-code {
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    line-height: 1.5;
    overflow-x: auto;
}
.code-line {
    white-space: pre;
    margin: 2px 0;
}
.line-number {
    color: #6c757d;
    user-select: none;
    margin-right: 15px;
    display: inline-block;
    width: 40px;
    text-align: right;
}
.keyword { color: #007bff; font-weight: bold; }
.string { color: #28a745; }
.comment { color: #6c757d; font-style: italic; }
.function { color: #e83e8c; }
.number { color: #fd7e14; }
.builtin { color: #17a2b8; }
</style>
CSS;
    
    return $css . $result;
}

这个简单的语法高亮功能,能为你的代码块添加颜色,区分关键字、字符串和注释,让代码在视觉上更有层次感。

最后,如果你想系统性地了解Python编码规范的所有细节,比如如何命名变量、如何书写文档字符串、如何组织导入语句,可以查阅完整的指南。

<?php
function getCodingStandards(string $language = 'zh'): array
{
    $standards = [
        'zh' => [
            [
                'title' => '命名规范',
                'items' => [
                    '变量名:使用小写字母和下划线,如:student_name',
                    '函数名:使用小写字母和下划线,如:calculate_average',
                    '类名:使用驼峰命名法,如:StudentRecord',
                    '常量名:使用大写字母和下划线,如:MAX_LENGTH'
                ]
            ],
            [
                'title' => '缩进规范',
                'items' => [
                    '使用4个空格进行缩进,不要使用制表符',
                    '函数定义和类定义之间空两行',
                    '同一代码块内的语句应对齐'
                ]
            ],
            [
                'title' => '注释规范',
                'items' => [
                    '单行注释以#开头,后面跟一个空格',
                    '多行注释使用三个双引号或单引号',
                    '函数和类应该有文档字符串(docstring)',
                    '复杂的代码段应该有注释说明'
                ]
            ],
            [
                'title' => '导入规范',
                'items' => [
                    '导入语句应放在文件顶部',
                    '每个导入应该单独一行',
                    '先导入标准库,再导入第三方库,最后导入本地模块',
                    '避免使用from module import *'
                ]
            ],
            [
                'title' => '其他规范',
                'items' => [
                    '每行不超过79个字符',
                    '在运算符前后和逗号后加空格',
                    '使用有意义的变量名',
                    '避免使用全局变量'
                ]
            ]
        ],
        'en' => [
            [
                'title' => 'Naming Conventions',
                'items' => [
                    'Variables: lowercase with underscores, e.g., student_name',
                    'Functions: lowercase with underscores, e.g., calculate_average',
                    'Classes: CamelCase, e.g., StudentRecord',
                    'Constants: UPPERCASE with underscores, e.g., MAX_LENGTH'
                ]
            ],
            [
                'title' => 'Indentation',
                'items' => [
                    'Use 4 spaces per indentation level, not tabs',
                    'Put two blank lines between function and class definitions',
                    'Align statements within the same code block'
                ]
            ],
            [
                'title' => 'Comments',
                'items' => [
                    'Single-line comments start with # followed by a space',
                    'Multi-line comments use triple quotes',
                    'Functions and classes should have docstrings',
                    'Complex code sections should have explanatory comments'
                ]
            ],
            [
                'title' => 'Imports',
                'items' => [
                    'Import statements should be at the top of the file',
                    'Each import should be on a separate line',
                    'Import standard libraries first, then third-party, then local modules',
                    'Avoid from module import *'
                ]
            ],
            [
                'title' => 'Other Standards',
                'items' => [
                    'Limit lines to 79 characters',
                    'Add spaces around operators and after commas',
                    'Use meaningful variable names',
                    'Avoid global variables'
                ]
            ]
        ],
        'es' => [
            [
                'title' => 'Convenciones de Nombres',
                'items' => [
                    'Variables: minúsculas con guiones bajos, ej., nombre_estudiante',
                    'Funciones: minúsculas con guiones bajos, ej., calcular_promedio',
                    'Clases: CamelCase, ej., RegistroEstudiante',
                    'Constantes: MAYÚSCULAS con guiones bajos, ej., LONGITUD_MAXIMA'
                ]
            ],
            [
                'title' => 'Indentación',
                'items' => [
                    'Use 4 espacios por nivel de indentación, no tabs',
                    'Poner dos líneas en blanco entre definiciones de funciones y clases',
                    'Alinear declaraciones dentro del mismo bloque de código'
                ]
            ],
            [
                'title' => 'Comentarios',
                'items' => [
                    'Los comentarios de una línea comienzan con # seguido de un espacio',
                    'Comentarios multi-línea usan comillas triples',
                    'Funciones y clases deben tener docstrings',
                    'Secciones de código complejas deben tener comentarios explicativos'
                ]
            ],
            [
                'title' => 'Importaciones',
                'items' => [
                    'Las declaraciones de importación deben estar en la parte superior del archivo',
                    'Cada importación debe estar en una línea separada',
                    'Importar bibliotecas estándar primero, luego terceras partes, luego módulos locales',
                    'Evitar from módulo import *'
                ]
            ],
            [
                'title' => 'Otros Estándares',
                'items' => [
                    'Limitar líneas a 79 caracteres',
                    'Agregar espacios alrededor de operadores y después de comas',
                    'Usar nombres de variables significativos',
                    'Evitar variables globales'
                ]
            ]
        ]
    ];
    
    return $standards[$language] ?? $standards['zh'];
}

记住,良好的代码规范不是束缚,而是一种高效沟通的语言。它让代码从个人笔记变成可协作的作品。从第一个程序开始就养成好习惯,未来的你会感谢现在的自己。

章节总结

当你第一次在屏幕上看到“Hello, World!”从自己写的Python程序中打印出来时,那种感觉就像掌握了某种魔法。这个简单的起点,通往的是一个广阔的世界。而写出能运行的代码只是第一步,写出清晰、优雅、易于理解的代码,才是真正开始编程。

回想一下你的第一个程序,也许它看起来是这样的:

<?php
function getFirstPythonExample(string $language = 'zh'): string
{
    $examples = [
        'en' => <<<'PYTHON'
# My first Python program
print("Hello, World!")

# Variable declaration
name = "Alice"
age = 25

# Print with variables
print(f"My name is {name} and I am {age} years old")

# Simple calculation
x = 10
y = 5
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
PYTHON,
        'zh' => <<<'PYTHON'
# 我的第一个Python程序
print("Hello, World!")

# 变量声明
name = "张三"
age = 25

# 打印带变量的内容
print(f"我的名字是{name},今年{age}岁")

# 简单计算
x = 10
y = 5
sum = x + y
print(f"{x}{y}的和是{sum}")
PYTHON,
        'es' => <<<'PYTHON'
# Mi primer programa en Python
print("¡Hola, Mundo!")

# Declaración de variables
name = "María"
age = 25

# Imprimir con variables
print(f"Mi nombre es {name} y tengo {age} años")

# Cálculo simple
x = 10
y = 5
sum = x + y
print(f"La suma de {x} y {y} es {sum}")
PYTHON,
    ];

    return $examples[$language] ?? $examples['zh'];
}

一个简单的 print 语句,是一切的开端。但即便是这样一行代码,也蕴含着规范。比如,引号和括号的使用是否一致?代码周围是否有不必要的空行?随着程序变长,这些细节会极大地影响可读性。

为什么需要规范呢?想象一下,如果每个作家都随意断句、不加标点,阅读将会多么困难。代码不仅是给计算机执行的指令,更是给人(包括未来的你自己)阅读的文档。一致的风格让团队协作顺畅,让维护和调试变得轻松。

那么,如何确保我们的代码是规范的呢?我们可以先验证最基本的语法是否正确:

<?php
function validatePythonCode(string $code): array
{
    $result = [
        'is_valid' => true,
        'errors' => [],
        'warnings' => [],
        'suggestions' => []
    ];

    // 检查代码是否为空
    if (empty(trim($code))) {
        $result['is_valid'] = false;
        $result['errors'][] = '代码不能为空';
        return $result;
    }

    // 检查是否有print语句(基础要求)
    if (!str_contains($code, 'print')) {
        $result['warnings'][] = '代码中未发现print语句,建议添加输出语句以便看到结果';
    }

    // 检查缩进是否一致(基础检查)
    $lines = explode("\n", $code);
    $indentationTypes = [];
    $previousIndentLength = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1; //1开始计数
        
        // 跳过空行
        if (strlen(trim($line)) === 0) {
            continue;
        }
        
        // 检查行首空格缩进
        preg_match('/^(\s*)/', $line, $matches);
        $indent = $matches[1] ?? '';
        
        // 检查缩进类型(空格或制表符)
        if (str_contains($indent, ' ') && str_contains($indent, "\t")) {
            $result['errors'][] = "第{$lineNumber}行: 混合使用了空格和制表符进行缩进";
            $result['is_valid'] = false;
        } elseif (str_contains($indent, ' ')) {
            $indentationTypes['space'] = true;
        } elseif (str_contains($indent, "\t")) {
            $indentationTypes['tab'] = true;
        }
        
        // 检查缩进长度
        $indentLength = strlen($indent);
        if ($indentLength > 0 && $indentLength % 4 !== 0) {
            $result['warnings'][] = "第{$lineNumber}行: 缩进使用了{$indentLength}个字符,建议使用4个空格进行缩进";
        }
        
        // 检查缩进是否合理(对比上一行)
        if ($lineNumber > 1) {
            $diff = $indentLength - $previousIndentLength;
            if ($diff > 4) {
                $result['warnings'][] = "第{$lineNumber}行: 缩进增加过多,建议一次只增加4个空格";
            }
        }
        
        $previousIndentLength = $indentLength;
    }
    
    // 检查是否混合使用了空格和制表符
    if (count($indentationTypes) > 1) {
        $result['errors'][] = "代码中混合使用了空格和制表符进行缩进,请统一使用一种缩进方式";
        $result['is_valid'] = false;
    }
    
    // 检查代码是否有明显语法错误(简单版)
    if (preg_match('/^(?:[\t ]*)(?:if|else|elif|for|while|def|class)\b/', $code, $matches) &&
        !preg_match('/:\s*$/', $code)) {
        $result['errors'][] = "控制流语句或函数定义缺少冒号(:)结尾";
        $result['is_valid'] = false;
    }
    
    // 检查括号是否匹配
    $stack = [];
    $pairs = [
        '(' => ')',
        '[' => ']',
        '{' => '}',
        '"' => '"',
        "'" => "'"
    ];
    
    for ($i = 0; $i < strlen($code); $i++) {
        $char = $code[$i];
        
        // 处理字符串字面量,跳过其中的括号
        if ($char === '"' || $char === "'") {
            if (empty($stack) || end($stack) !== $char) {
                $stack[] = $char;
            } else {
                array_pop($stack);
            }
            continue;
        }
        
        // 如果在字符串中,跳过括号检查
        if (!empty($stack) && (end($stack) === '"' || end($stack) === "'")) {
            continue;
        }
        
        // 处理括号
        if (in_array($char, ['(', '[', '{'])) {
            $stack[] = $char;
        } elseif (in_array($char, [')', ']', '}'])) {
            $last = array_pop($stack);
            if ($last === null || $pairs[$last] !== $char) {
                $result['errors'][] = "括号不匹配: 第" . ($i + 1) . "个字符'{$char}'没有对应的开括号";
                $result['is_valid'] = false;
            }
        }
    }
    
    // 检查未关闭的括号
    if (!empty($stack)) {
        foreach ($stack as $bracket) {
            $result['errors'][] = "未关闭的括号: '{$bracket}'";
        }
        $result['is_valid'] = false;
    }
    
    // 检查常见的拼写错误
    $commonMistakes = [
        'prnt' => 'print',
        'def ' => 'def ',
        'class ' => 'class ',
        'whlie' => 'while',
        'for ' => 'for ',
        'if ' => 'if ',
        'else:' => 'else:'
    ];
    
    foreach ($commonMistakes as $wrong => $correct) {
        if (preg_match('/\b' . preg_quote($wrong, '/') . '\b/', $code) && 
            !str_contains($code, $correct)) {
            $result['suggestions'][] = "可能拼写错误: '{$wrong}',应该是'{$correct}'吗?";
        }
    }
    
    // 如果代码有效,添加一个积极的建议
    if ($result['is_valid'] && empty($result['errors'])) {
        $result['suggestions'][] = '代码基本语法正确,可以考虑添加注释或优化代码结构';
    }

    return $result;
}

语法正确是基石。接着,我们可以用更细致的工具来检查它是否符合Python社区广泛采用的PEP8规范:

<?php
function checkPEP8Compliance(string $code): array
{
    $result = [
        'score' => 100, // 初始分数
        'violations' => [],
        'compliance_percentage' => 0
    ];
    
    $lines = explode("\n", $code);
    $violationCount = 0;
    $totalChecks = 0;
    
    foreach ($lines as $lineNumber => $line) {
        $lineNumber += 1;
        $totalChecks += 5; // 每行检查5个项目
        
        // 1. 检查行长度(PEP8: 不超过79字符)
        if (strlen($line) > 79) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => sprintf('行长度 %d 字符超过PEP8建议的79字符', strlen($line))
            ];
        }
        
        // 2. 检查行尾空白
        if (preg_match('/\s+$/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'error',
                'message' => '行尾存在多余空白字符'
            ];
        }
        
        // 3. 检查运算符周围的空格
        if (preg_match('/[=+\-*\/<>!]=/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '建议在运算符周围添加空格以提高可读性'
            ];
        }
        
        // 4. 检查注释格式
        if (preg_match('/^[ \t]*#[a-zA-Z]/', $line)) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'suggestion',
                'message' => '注释应以空格开始,例如:# 注释内容'
            ];
        }
        
        // 5. 检查导入语句位置(简化检查)
        if (strpos($line, 'import ') !== false && $lineNumber > 10) {
            $violationCount++;
            $result['violations'][] = [
                'line' => $lineNumber,
                'type' => 'warning',
                'message' => '导入语句应位于文件顶部'
            ];
        }
    }
    
    // 计算合规率
    if ($totalChecks > 0) {
        $complianceRate = (($totalChecks - $violationCount) / $totalChecks) * 100;
        $result['compliance_percentage'] = round($complianceRate, 1);
        $result['score'] = max(0, $complianceRate);
    }
    
    return $result;
}

这个函数会像一个耐心的教练,指出哪里该加空格,哪里命名可以改进。根据建议调整后,你的代码会变得整洁许多。如果需要快速统一格式,比如调整缩进,可以使用:

<?php
function formatPythonCode(string $code, int $indentSize = 4): string
{
    // 移除首尾空白
    $code = trim($code);
    
    // 标准化换行符
    $code = str_replace(["\r\n", "\r"], "\n", $code);
    
    $lines = explode("\n", $code);
    $formattedLines = [];
    $currentIndent = 0;
    
    foreach ($lines as $line) {
        $trimmedLine = ltrim($line);
        
        // 跳过空行,但保留逻辑块之间的空行
        if (empty($trimmedLine)) {
            if (!empty(end($formattedLines))) {
                $formattedLines[] = '';
            }
            continue;
        }
        
        // 计算新的缩进级别
        $originalIndent = strlen($line) - strlen($trimmedLine);
        $indentLevel = (int)($originalIndent / $indentSize);
        
        // 应用新的缩进
        $newIndent = str_repeat(' ', $indentLevel * $indentSize);
        $formattedLines[] = $newIndent . $trimmedLine;
    }
    
    // 移除多余的空行(连续空行保留一个)
    $result = [];
    $previousEmpty = false;
    
    foreach ($formattedLines as $line) {
        if (empty($line)) {
            if (!$previousEmpty) {
                $result[] = '';
                $previousEmpty = true;
            }
        } else {
            $result[] = $line;
            $previousEmpty = false;
        }
    }
    
    // 确保最后一行不是空行
    while (!empty($result) && empty(end($result))) {
        array_pop($result);
    }
    
    return implode("\n", $result);
}

经过格式化的代码,结构一目了然。为了让它在教程或文档中更美观,我们还可以为其加上语法高亮:

<?php
function highlightPythonSyntax(string $code): string
{
    // 定义语法高亮规则
    $patterns = [
        // 关键字
        '/\b(def|class|if|else|elif|for|while|try|except|finally|import|from|as|return|break|continue|pass|and|or|not|in|is|None|True|False)\b/' 
            => '<span class="keyword">$1</span>',
        
        // 字符串
        '/([\'"])(.*?)\1/' 
            => '<span class="string">$1$2$1</span>',
        
        // 注释
        '/#(.*)$/m' 
            => '<span class="comment">#$1</span>',
        
        // 函数调用
        '/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/' 
            => '<span class="function">$1</span>(',
        
        // 数字
        '/\b(\d+\.?\d*)\b/' 
            => '<span class="number">$1</span>',
        
        // 内置函数
        '/\b(print|input|len|str|int|float|type|range|list|dict|set|tuple)\b/' 
            => '<span class="builtin">$1</span>',
    ];
    
    // 应用所有规则
    $highlighted = $code;
    foreach ($patterns as $pattern => $replacement) {
        $highlighted = preg_replace($pattern, $replacement, $highlighted);
    }
    
    // 添加行号
    $lines = explode("\n", $highlighted);
    $numberedLines = [];
    
    foreach ($lines as $i => $line) {
        $lineNumber = $i + 1;
        $numberedLines[] = sprintf(
            '<div class="code-line"><span class="line-number">%3d</span> <span class="line-content">%s</span></div>',
            $lineNumber,
            $line
        );
    }
    
    // 包裹在代码块中
    $result = '<div class="python-code">' . implode("\n", $numberedLines) . '</div>';
    
    // 添加CSS样式
    $css = <<<'CSS'
<style>
.python-code {
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    line-height: 1.5;
    overflow-x: auto;
}
.code-line {
    white-space: pre;
    margin: 2px 0;
}
.line-number {
    color: #6c757d;
    user-select: none;
    margin-right: 15px;
    display: inline-block;
    width: 40px;
    text-align: right;
}
.keyword { color: #007bff; font-weight: bold; }
.string { color: #28a745; }
.comment { color: #6c757d; font-style: italic; }
.function { color: #e83e8c; }
.number { color: #fd7e14; }
.builtin { color: #17a2b8; }
</style>
CSS;
    
    return $css . $result;
}

随着你编写的程序越来越复杂,了解代码的结构和复杂度也很有帮助。你可以分析一下自己的小项目:

<?php
function analyzeCodeComplexity(string $code): array
{
    $analysis = [
        'metrics' => [
            'total_lines' => 0,
            'code_lines' => 0,
            'comment_lines' => 0,
            'blank_lines' => 0,
            'function_count' => 0,
            'average_function_length' => 0,
            'cyclomatic_complexity' => 0
        ],
        'functions' => [],
        'complexity_level' => 'low'
    ];
    
    // 将代码按行分割
    $lines = explode("\n", $code);
    $analysis['metrics']['total_lines'] = count($lines);
    
    $inMultilineComment = false; // 是否在多行注释中
    $currentFunction = null;     // 当前解析的函数信息
    $functionLines = 0;          // 当前函数的行数
    $functionComplexity = 1;     // 当前函数的圈复杂度(基础为1)
    
    foreach ($lines as $lineNumber => $line) {
        $trimmedLine = trim($line);
        $lineNumber++; //1开始
        
        // 检查空行
        if (empty($trimmedLine)) {
            $analysis['metrics']['blank_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理多行注释(Python的三引号注释)
        $hasMultiStart = strpos($trimmedLine, '"""') === 0 || strpos($trimmedLine, "'''") === 0;
        $hasMultiEnd = substr_count($trimmedLine, '"""') >= 2 || substr_count($trimmedLine, "'''") >= 2;
        
        // 多行注释开始
        if ($hasMultiStart && !$inMultilineComment) {
            $inMultilineComment = true;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 多行注释结束
        if ($hasMultiEnd && $inMultilineComment) {
            $inMultilineComment = false;
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 在多行注释中
        if ($inMultilineComment) {
            $analysis['metrics']['comment_lines']++;
            continue;
        }
        
        // 处理单行注释(以#开头)
        if (strpos($trimmedLine, '#') === 0) {
            $analysis['metrics']['comment_lines']++;
            if ($currentFunction !== null) {
                $functionLines++;
            }
            continue;
        }
        
        // 处理内联注释
        $inlineCommentPos = strpos($trimmedLine, '#');
        if ($inlineCommentPos !== false) {
            $analysis['metrics']['comment_lines']++;
            $trimmedLine = trim(substr($trimmedLine, 0, $inlineCommentPos));
            if (empty($trimmedLine)) {
                continue;
            }
        }
        
        // 识别函数定义(以def开头)
        if (strpos($trimmedLine, 'def ') === 0) {
            // 如果有正在统计的函数,先保存
            if ($currentFunction !== null) {
                $analysis['functions'][] = [
                    'name' => $currentFunction,
                    'lines' => $functionLines,
                    'complexity' => $functionComplexity
                ];
            }
            
            // 解析函数名
            preg_match('/def\s+(\w+)\s*\(/', $trimmedLine, $matches);
            $currentFunction = isset($matches[1]) ? $matches[1] : 'anonymous_function';
            $analysis['metrics']['function_count']++;
            $functionLines = 1; // 函数定义行
            $functionComplexity = 1; // 重置圈复杂度
            
            // 检查函数定义中是否有默认参数(会增加复杂度)
            if (strpos($trimmedLine, '=') !== false) {
                $functionComplexity++;
            }
        } 
        // 如果是代码行且不在函数中
        elseif ($currentFunction === null) {
            $analysis['metrics']['code_lines']++;
            
            // 检查控制流语句(增加整体复杂度)
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $analysis['metrics']['cyclomatic_complexity']++;
            }
        }
        // 函数内的代码行
        else {
            $functionLines++;
            $analysis['metrics']['code_lines']++;
            
            // 计算函数内的圈复杂度
            if (preg_match('/\b(if|elif|for|while|try|except|finally|with)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查逻辑运算符
            if (preg_match('/\b(and|or)\b/', $trimmedLine)) {
                $functionComplexity++;
            }
            
            // 检查三元运算符
            if (strpos($trimmedLine, ' if ') !== false && strpos($trimmedLine, ' else ') !== false) {
                $functionComplexity++;
            }
        }
    }
    
    // 处理最后一个函数
    if ($currentFunction !== null) {
        $analysis['functions'][] = [
            'name' => $currentFunction,
            'lines' => $functionLines,
            'complexity' => $functionComplexity
        ];
    }
    
    // 计算平均函数长度
    if ($analysis['metrics']['function_count'] > 0) {
        $totalFunctionLines = 0;
        foreach ($analysis['functions'] as $func) {
            $totalFunctionLines += $func['lines'];
        }
        $analysis['metrics']['average_function_length'] = 
            round($totalFunctionLines / $analysis['metrics']['function_count'], 2);
    }
    
    // 计算平均圈复杂度
    if (!empty($analysis['functions'])) {
        $totalComplexity = 0;
        foreach ($analysis['functions'] as $func) {
            $totalComplexity += $func['complexity'];
        }
        $analysis['metrics']['cyclomatic_complexity'] = 
            round($totalComplexity / count($analysis['functions']), 2);
    }
    
    // 确定复杂度级别
    $avgComplexity = $analysis['metrics']['cyclomatic_complexity'];
    if ($avgComplexity < 5) {
        $analysis['complexity_level'] = 'low';
    } elseif ($avgComplexity >= 5 && $avgComplexity < 10) {
        $analysis['complexity_level'] = 'medium';
    } else {
        $analysis['complexity_level'] = 'high';
    }
    
    return $analysis;
}

最后,如果你想系统地学习或查阅Python的编码规范,这里有一份完整的指南:

<?php
function getCodingStandards(string $language = 'zh'): array
{
    $standards = [
        'zh' => [
            [
                'title' => '命名规范',
                'items' => [
                    '变量名:使用小写字母和下划线,如:student_name',
                    '函数名:使用小写字母和下划线,如:calculate_average',
                    '类名:使用驼峰命名法,如:StudentRecord',
                    '常量名:使用大写字母和下划线,如:MAX_LENGTH'
                ]
            ],
            [
                'title' => '缩进规范',
                'items' => [
                    '使用4个空格进行缩进,不要使用制表符',
                    '函数定义和类定义之间空两行',
                    '同一代码块内的语句应对齐'
                ]
            ],
            [
                'title' => '注释规范',
                'items' => [
                    '单行注释以#开头,后面跟一个空格',
                    '多行注释使用三个双引号或单引号',
                    '函数和类应该有文档字符串(docstring)',
                    '复杂的代码段应该有注释说明'
                ]
            ],
            [
                'title' => '导入规范',
                'items' => [
                    '导入语句应放在文件顶部',
                    '每个导入应该单独一行',
                    '先导入标准库,再导入第三方库,最后导入本地模块',
                    '避免使用from module import *'
                ]
            ],
            [
                'title' => '其他规范',
                'items' => [
                    '每行不超过79个字符',
                    '在运算符前后和逗号后加空格',
                    '使用有意义的变量名',
                    '避免使用全局变量'
                ]
            ]
        ],
        'en' => [
            [
                'title' => 'Naming Conventions',
                'items' => [
                    'Variables: lowercase with underscores, e.g., student_name',
                    'Functions: lowercase with underscores, e.g., calculate_average',
                    'Classes: CamelCase, e.g., StudentRecord',
                    'Constants: UPPERCASE with underscores, e.g., MAX_LENGTH'
                ]
            ],
            [
                'title' => 'Indentation',
                'items' => [
                    'Use 4 spaces per indentation level, not tabs',
                    'Put two blank lines between function and class definitions',
                    'Align statements within the same code block'
                ]
            ],
            [
                'title' => 'Comments',
                'items' => [
                    'Single-line comments start with # followed by a space',
                    'Multi-line comments use triple quotes',
                    'Functions and classes should have docstrings',
                    'Complex code sections should have explanatory comments'
                ]
            ],
            [
                'title' => 'Imports',
                'items' => [
                    'Import statements should be at the top of the file',
                    'Each import should be on a separate line',
                    'Import standard libraries first, then third-party, then local modules',
                    'Avoid from module import *'
                ]
            ],
            [
                'title' => 'Other Standards',
                'items' => [
                    'Limit lines to 79 characters',
                    'Add spaces around operators and after commas',
                    'Use meaningful variable names',
                    'Avoid global variables'
                ]
            ]
        ],
        'es' => [
            [
                'title' => 'Convenciones de Nombres',
                'items' => [
                    'Variables: minúsculas con guiones bajos, ej., nombre_estudiante',
                    'Funciones: minúsculas con guiones bajos, ej., calcular_promedio',
                    'Clases: CamelCase, ej., RegistroEstudiante',
                    'Constantes: MAYÚSCULAS con guiones bajos, ej., LONGITUD_MAXIMA'
                ]
            ],
            [
                'title' => 'Indentación',
                'items' => [
                    'Use 4 espacios por nivel de indentación, no tabs',
                    'Poner dos líneas en blanco entre definiciones de funciones y clases',
                    'Alinear declaraciones dentro del mismo bloque de código'
                ]
            ],
            [
                'title' => 'Comentarios',
                'items' => [
                    'Los comentarios de una línea comienzan con # seguido de un espacio',
                    'Comentarios multi-línea usan comillas triples',
                    'Funciones y clases deben tener docstrings',
                    'Secciones de código complejas deben tener comentarios explicativos'
                ]
            ],
            [
                'title' => 'Importaciones',
                'items' => [
                    'Las declaraciones de importación deben estar en la parte superior del archivo',
                    'Cada importación debe estar en una línea separada',
                    'Importar bibliotecas estándar primero, luego terceras partes, luego módulos locales',
                    'Evitar from módulo import *'
                ]
            ],
            [
                'title' => 'Otros Estándares',
                'items' => [
                    'Limitar líneas a 79 caracteres',
                    'Agregar espacios alrededor de operadores y después de comas',
                    'Usar nombres de variables significativos',
                    'Evitar variables globales'
                ]
            ]
        ]
    ];
    
    return $standards[$language] ?? $standards['zh'];
}

规范不是束缚创造力的枷锁,而是让创意清晰表达的框架。从写下第一个 print(“Hello, World!”) 开始,就试着用这些工具和习惯来要求自己。好的开始,是养成优秀编程习惯的一半。

内容概要:本文是由从业8年的软件开发工程师老张撰写的超详细Python安装使用教程,旨在帮助零基础的新手快速上手Python编程。文章首先介绍了Python的基本概念及其核心特点,如简单易学、功能强大、跨平台性和丰富的生态系统。接着详细阐述了Python的应用场景,包括数据分析、人工智能、网络开发、自动化脚本和科学计算等。随后,针对不同操作系统(Windows、macOS、Linux)提供了详细的Python 3.12.0版本安装步骤,并介绍了安装后的必备配置,如包管理工具pip的使用、虚拟环境的创建和激活,以及开发工具的选择(IDLE、PyCharm、VS Code)。最后,通过编写第一个Python程序“Hello World”引导读者进行实践,并提供了常见问题的解决方案,帮助读者顺利安装和使用Python。 适合人群:对编程感兴趣的初学者,特别是那些想要学习Python但缺乏安装和配置经验的人群。 使用场景及目标:①帮助新手了解Python的基础知识和优势;②指导用户在不同操作系统上正确安装Python 3.12.0;③教会用户配置开发环境和使用常用工具;④通过编写简单的Python程序培养编程兴趣和实践能力。 其他说明:编程是一项实践性很强的技能,建议读者每天花30分钟进行代码练习,逐步积累经验。文中还提到后续会分享更多关于数据分析、网络开发、人工智能等领域的Python进阶教程,鼓励读者持续关注和学习。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸王大陆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值