Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Python 基本语法和缩进:完整的初学者指南_创想鸟

Python 基本语法和缩进:完整的初学者指南

python 基本语法和缩进:完整的初学者指南

当你第一次学习编程时,python 因一个特殊原因而脱颖而出:它的设计目的几乎像英语一样阅读。与使用大量符号和括号的其他编程语言不同,python 依赖于简单、干净的格式,使您的代码看起来像组织良好的文档。

将 python 的语法视为语言的语法规则。正如英语有关于如何构造句子以使含义清晰的规则一样,python 也有关于如何编写代码以便人类和计算机都能理解的规则。

理解python的基本语法

构建模块

让我们从最简单的 python 语法元素开始:

# this is a comment - python ignores anything after the '#' symbolstudent_name = "alice"    # a variable holding text (string)student_age = 15         # a variable holding a number (integer)# using variables in a sentence (string formatting)print(f"hello, my name is {student_name} and i'm {student_age} years old.")

在此示例中,我们使用了 python 的几个基本元素:

评论(以#开头的行)变量(student_name 和 student_age)字符串格式(f”…” 语法)打印功能

基本操作

python可以像计算器一样进行计算和比较:

# basic math operationstotal_score = 95 + 87    # additionaverage = total_score / 2 # division# comparisonsif student_age >= 15:    print(f"{student_name} can take advanced classes")

python 的核心:理解缩进

这就是 python 真正独特的地方:python 使用缩进,而不是使用括号或特殊符号将代码组合在一起。乍一看这可能看起来很奇怪,但它使 python 代码异常清晰易读。

立即学习“Python免费学习笔记(深入)”;

缩进如何创建结构

将缩进想象为组织详细大纲的方式:

def make_sandwich():    print("1. get two slices of bread")  # first level    if has_cheese:        print("2. add cheese")           # second level        print("3. add tomatoes")         # still second level    else:        print("2. add butter")           # second level in else block    print("4. put the slices together")  # back to first level

每个缩进块都告诉 python“这些行属于一起”。这就像在大纲中创建一个子列表 – “if has_cheese:”下缩进的所有内容都是该条件的一部分。

缩进规则

让我们看看python缩进的关键规则:

def process_grade(score):    # rule 1: use exactly 4 spaces for each indentation level    if score >= 90:        print("excellent!")        if score == 100:            print("perfect score!")    # rule 2: aligned blocks work together    elif score >= 80:        print("good job!")        print("keep it up!")  # this line is part of the elif block    # rule 3: unindented lines end the block    print("processing complete")  # this runs regardless of score

嵌套缩进:更深入

随着您的程序变得更加复杂,您通常需要多级缩进:

def check_weather(temperature, is_raining):    # first level: inside function    if temperature > 70:        # second level: inside if        if is_raining:            # third level: nested condition            print("it's warm but raining")            print("take an umbrella")        else:            print("it's a warm, sunny day")            print("perfect for outdoors")    else:        print("it's cool outside")        print("take a jacket")

复杂的结构和压痕

让我们看一个更复杂的示例,它展示了缩进如何帮助组织代码:

def process_student_grades(students):    for student in students:            # first level loop        print(f"checking {student['name']}'s grades...")        total = 0        for grade in student['grades']: # second level loop            if grade > 90:              # third level condition                print("outstanding!")            total += grade        average = total / len(student['grades'])        # back to first loop level        if average >= 90:            print("honor roll")            if student['attendance'] > 95:  # another level                print("perfect attendance award")

常见模式和最佳实践

处理多种条件

# good: clear and easy to followdef check_eligibility(age, grade, attendance):    if age < 18:        return "too young"    if grade < 70:        return "grades too low"    if attendance = 18:        if grade >= 70:            if attendance >= 80:                return "eligible"            else:                return "attendance too low"        else:            return "grades too low"    else:        return "too young"

使用函数和类

class student:    def __init__(self, name):        self.name = name        self.grades = []    def add_grade(self, grade):        # notice the consistent indentation in methods        if isinstance(grade, (int, float)):            if 0 <= grade <= 100:                self.grades.append(grade)                print(f"grade {grade} added")            else:                print("grade must be between 0 and 100")        else:            print("grade must be a number")

常见错误及其解决方法

缩进错误

# wrong - inconsistent indentationif score > 90:print("great job!")    # error: no indentation    print("keep it up!")   # error: inconsistent indentation# right - proper indentationif score > 90:    print("great job!")    print("keep it up!")

混合制表符和空格

# wrong - mixed tabs and spaces (don't do this!)def calculate_average(numbers):    total = 0    count = 0    # this line uses a tab    for num in numbers:    # this line uses spaces        total += num

练习:将它们放在一起

尝试编写这个程序来练习缩进和语法:

def grade_assignment(score, late_days):    # Start with the base score    final_score = score    # Check if the assignment is late    if late_days > 0:        if late_days <= 5:            # Deduct 2 points per late day            final_score -= (late_days * 2)        else:            # Maximum lateness penalty            final_score -= 10    # Ensure score doesn't go below 0    if final_score = 90:        return "A", final_score    elif final_score >= 80:        return "B", final_score    elif final_score >= 70:        return "C", final_score    else:        return "F", final_score# Test the functionscore = 95late_days = 2letter_grade, final_score = grade_assignment(score, late_days)print(f"Original Score: {score}")print(f"Late Days: {late_days}")print(f"Final Score: {final_score}")print(f"Letter Grade: {letter_grade}")

要点

python 使用缩进来理解代码结构每一级缩进始终使用 4 个空格在整个代码中保持缩进一致更简单、更扁平的代码结构通常比深度嵌套的代码更好适当的缩进使代码更具可读性并有助于防止错误

下一步

现在您已经了解了 python 的基本语法和缩进:

练习编写简单的程序,重点关注正确的缩进了解不同的数据类型(字符串、数字、列表)探索函数和类研究循环和控制结构开始使用 python 模块和库

记住:良好的缩进习惯是成为熟练python程序员的基础。花点时间掌握这些概念,剩下的就会水到渠成!

以上就是Python 基本语法和缩进:完整的初学者指南的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1354802.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
在 Conky 面板上显示 Python 脚本输出
上一篇 2025年12月13日 18:48:31
Python Day-String 使用循环函数逻辑
下一篇 2025年12月13日 18:48:39

相关推荐

发表回复

登录后才能评论
关注微信