當你第一次學習程式設計時,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中文網其他相關文章!