When you're first learning to program, Python stands out for a special reason: it's designed to be read almost like English. Unlike other programming languages that use lots of symbols and brackets, Python relies on simple, clean formatting that makes your code look like a well-organized document.
Think of Python's syntax like the grammar rules of a language. Just as English has rules about how to structure sentences to make meaning clear, Python has rules about how to write code so both humans and computers can understand it.
Let's start with the simplest elements of Python syntax:
# 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.")
In this example, we're using several basic elements of Python:
Python can perform calculations and comparisons just like a calculator:
# 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")
Here's where Python gets truly unique: instead of using brackets or special symbols to group code together, Python uses indentation. This might seem strange at first, but it makes Python code exceptionally clear and readable.
Think of indentation like the way you might organize a detailed outline:
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
Each indented block tells Python "these lines belong together." It's like creating a sub-list in an outline – everything indented under "if has_cheese:" is part of that condition.
Let's look at the key rules for Python indentation:
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
As your programs get more complex, you'll often need multiple levels of indentation:
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")
Let's look at a more complex example that shows how indentation helps organize code:
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
Try writing this program to practice indentation and syntax:
# 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.")
Now that you understand Python's basic syntax and indentation:
Remember: Good indentation habits form the foundation of becoming a skilled Python programmer. Take your time to master these concepts, and the rest will follow naturally!
The above is the detailed content of Python Basic Syntax and Indentation: The Complete Beginners Guide. For more information, please follow other related articles on the PHP Chinese website!