Lesson 2.1: Python Syntax and Indentation
Introduction:
Python is known for its clean and readable syntax, which makes it ideal for beginners. Unlike many other programming languages, Python uses indentation (whitespace) to define code blocks instead of braces {}. Understanding Python syntax and indentation rules is crucial for writing correct and efficient code.
Python Syntax Basics:
-
Statements:
-
A Python program is made up of statements that are executed line by line.
-
-
Comments:
-
Comments are used to explain code and are ignored during execution.
-
-
Case Sensitivity:
-
Python is case-sensitive. Variable names
nameandNameare considered different.
-
-
Python Keywords:
-
Reserved words in Python that have special meaning, e.g.,
if,else,for,while,def,class. -
Cannot be used as variable names.
-
Indentation in Python:
-
Indentation defines a block of code (like the body of a loop, function, or conditional statement).
-
Typically, 4 spaces are used per indentation level.
-
Incorrect indentation leads to
IndentationError.
Example:
Important Rules:
-
Do not mix tabs and spaces for indentation.
-
Consistent indentation is mandatory for loops, conditionals, functions, and classes.
Practical Tip:
-
Always use an IDE like VS Code or PyCharm that highlights indentation errors automatically.
-
Writing readable code with proper indentation improves maintainability and reduces errors.
Learning Outcome of This Lesson:
-
Understand Python’s basic syntax and structure
-
Learn how to write single-line statements and comments
-
Recognize Python’s case sensitivity and reserved keywords
-
Apply correct indentation to define code blocks and avoid errors
