0

0

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

花韻仙語

花韻仙語

发布时间:2024-12-12 13:51:00

|

417人浏览过

|

来源于dev.to

转载

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

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

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

理解python的基本语法

构建模块

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

# this is a comment - python ignores anything after the '#' symbol
student_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 operations
total_score = 95 + 87    # addition
average = total_score / 2 # division

# comparisons
if student_age >= 15:
    print(f"{student_name} can take advanced classes")

python 的核心:理解缩进

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

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

缩进如何创建结构

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

Remove.bg
Remove.bg

AI在线抠图软件,图片去除背景

下载
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 follow
def check_eligibility(age, grade, attendance):
    if age < 18:
        return "too young"

    if grade < 70:
        return "grades too low"

    if attendance < 80:
        return "attendance too low"

    return "eligible"

# avoid: too many nested levels
def check_eligibility_nested(age, grade, attendance):
    if age >= 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 indentation
if score > 90:
print("great job!")    # error: no indentation
    print("keep it up!")   # error: inconsistent indentation

# right - proper indentation
if 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 < 0:
        final_score = 0

    # Determine letter grade
    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 function
score = 95
late_days = 2
letter_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}")

要点

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

下一步

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

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

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

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

772

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

661

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

764

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

679

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1365

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

569

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

579

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

730

2023.08.11

菜鸟裹裹入口以及教程汇总
菜鸟裹裹入口以及教程汇总

本专题整合了菜鸟裹裹入口地址及教程分享,阅读专题下面的文章了解更多详细内容。

0

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 13.9万人学习

Django 教程
Django 教程

共28课时 | 3.4万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号