当你第一次学习编程时,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 的几个基本元素:
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 代码异常清晰易读。
将缩进想象为组织详细大纲的方式:
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
尝试编写这个程序来练习缩进和语法:
# 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 的基本语法和缩进:
记住:良好的缩进习惯是成为熟练Python程序员的基础。花点时间掌握这些概念,剩下的就会水到渠成!
以上是Python 基本语法和缩进:完整的初学者指南的详细内容。更多信息请关注PHP中文网其他相关文章!