Python Master Course V2 — 004. Understanding Python Syntax and Structure
Module 01 · Python foundations · Lesson 004 / 200
Understanding Python Syntax and Structure
SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 01Write Python that the interpreter can understand and other developers can read. Master indentation, statements, identifiers, comments, expressions, code blocks and the anatomy of a clean Python file.
Lesson 004 / 200Beginner → Professional Habits45–65 minutes10+ Code ExamplesPractice + Mini-ProjectIn this lesson · 12 sections + self-check
- 🎬 Your Lesson Video
- Lesson Roadmap
- 1. Learning Objectives & Prerequisites
- 2. Syntax, Semantics and Program Behavior
- 3. Indentation: Python’s Structural Backbone
- 4. Colons, Brackets, Quotes, Names and Keywords
- 5. Writing Readable, Well-Structured Python
- 6. Recognizing and Fixing Common Errors
- 7. Guided Mini-Project — Professional Order Summary
- 8. Guided Practice, Exercises & Challenge
- 9. Knowledge Check
- 10. Professional Checklist & Lesson Summary
- Interactive self-check
🎬 Your Lesson Video
Video coming soon. This dedicated lesson video area is ready for an embedded player or external video link.
Video URL placeholder: [ADD_LESSON_004_VIDEO_URL]
Lesson Roadmap
OutcomesSyntax vs meaningIndentationSymbols & identifiersClean code structureDebuggingMini-projectExercisesQuiz1. Learning Objectives & Prerequisites
Prerequisites: Complete Lessons 001–003, have Python 3 installed, and know how to run a .py file from an editor or terminal. All examples use the Python 3 standard library, so no third-party packages are required.
After this lesson you should be able to:
- Distinguish valid syntax from a logically correct program.
- Describe simple statements, compound statements and code blocks.
- Use consistent four-space indentation in
if,foranddefblocks. - Understand how colons, parentheses, quotation marks, comments and blank lines work.
- Choose valid, descriptive Python identifiers and recognize case sensitivity.
- Split long expressions cleanly and organize a readable script.
- Diagnose basic
SyntaxError,IndentationErrorand related issues.
2. Syntax, Semantics and Program Behavior
Syntax is the set of rules for writing code that Python can parse. Semantics concerns what those instructions mean. A syntactically valid program can still calculate the wrong answer; conversely, a sensible idea written with invalid syntax will not run.
Example 1 — A valid program
product = "Notebook"
unit_price = 80
quantity = 3
total = unit_price * quantity
print("Product:", product)
print("Amount:", total)
Each assignment creates a name associated with a value. Multiplication produces a total, and print() displays readable output. Python accepts the syntax and the arithmetic matches the intended calculation.
Example 2 — Valid syntax, incorrect logic
unit_price = 80
quantity = 3
total = unit_price + quantity # Wrong operation
print(total)
This program runs without a syntax error but produces the wrong amount. The correct formula should use * rather than +. A professional developer verifies requirements and outcomes, not merely whether the program executes.
Statements vs. expressions
An expression produces a value, such as 5 * 4 or quantity > 0. A statement performs an operation or controls execution, such as total = 20, print(total) or an if block. Python permits expression statements, including function calls.
number = 10 # Assignment statement
is_even = number % 2 == 0 # Expression used in assignment
print(is_even) # Function-call expression as a statement
3. Indentation: Python’s Structural Backbone
In Python, leading whitespace is not just decoration. Indentation identifies which statements belong inside a block. Many other languages surround blocks with braces; Python uses indentation to make structure visible in the source code.
Example 3 — Conditional block
marks = 72
if marks >= 50:
print("Result: Pass")
print("You have met the minimum requirement.")
print("Assessment complete.")
The two indented print() calls are inside the if block. The final statement is back at the outer indentation level, so it runs regardless of the condition. The colon introduces the block, and the next statement is indented.
Example 4 — An if/else block
temperature = 29
if temperature >= 35:
print("Very hot day")
else:
print("Temperature is below 35 degrees")
print("Weather check finished")
if and else align with each other. Their bodies are indented one level further. Align related branches at the same level.
Example 5 — Nested blocks
is_registered = True
score = 88
if is_registered:
if score >= 80:
print("Eligible for distinction")
else:
print("Registered, but below distinction")
else:
print("Registration required")
Each nesting level adds four spaces. Visually trace the indentation to identify which else belongs to which if.
TabError or confusing alignment.Example 6 — Loop block
for lesson_number in range(1, 4):
print("Starting lesson", lesson_number)
print("All lessons in this demo are listed.")
Indentation tells Python which statement repeats. Only the first print() is inside the loop. The final message appears once after the loop completes.
4. Colons, Brackets, Quotes, Names and Keywords
4.1 Colons and compound statements
A colon (:) appears at the end of headers that introduce an indented suite, such as if, for, while, def, class and try. A missing colon is a common beginner syntax mistake.
# Valid:
if 5 > 2:
print("Five is greater than two")
4.2 Parentheses, brackets and braces
| Symbol | Typical role | Example |
|---|---|---|
( ) | Function calls and expression grouping; tuples | print((3 + 2) * 4) |
[ ] | Lists and indexing | scores = [88, 92] |
{ } | Dictionaries and sets | person = {"name": "Anu"} |
: | Starts a block; also used in dictionaries and slicing | if ready: |
# | Begins an ordinary comment outside strings | # Readable note |
Example 7 — Balanced delimiters and operator precedence
base = 12
extra = 3
multiplier = 2
without_grouping = base + extra * multiplier
with_grouping = (base + extra) * multiplier
print(without_grouping)
print(with_grouping)
Parentheses make the intended arithmetic order explicit. Missing closing delimiters are another frequent source of SyntaxError.
4.3 Strings and quotation marks
Python accepts single or double quotes for ordinary string literals. The opening and closing quotation marks must match. Triple-quoted literals support multi-line text and are also used for documentation strings (docstrings).
Example 8 — Strings and special characters
first = 'Hello'
second = "Python"
message = "Line one\nLine two"
print(first, second)
print(message)
n means a newline inside the string. Quotes inside strings can be handled by choosing the other quote style or escaping the quote.
4.4 Valid identifiers
Identifiers are names assigned to variables, functions, classes and other objects. They can contain letters, digits and underscores, but cannot begin with a digit. Python is case-sensitive, so score and Score are different names. Python also supports many Unicode identifiers, but simple descriptive ASCII names are usually easier to share across tools.
| Valid | Invalid | Why |
|---|---|---|
student_name | student-name | Hyphen means subtraction |
score2 | 2score | Cannot start with a digit |
total_amount | total amount | Spaces are not allowed |
pass_mark | class | Reserved keyword |
Example 9 — Case sensitivity
student = "Anita"
Student = "Vikram"
print(student)
print(Student)
Though valid, names that differ only by capitalization can confuse readers. Prefer descriptive lowercase names separated by underscores, such as student_name.
4.5 Reserved words
Words such as if, else, for, while, def, return, class, True, False and None have special meanings and cannot be used as ordinary identifiers. A few words are context-sensitive soft keywords in newer Python versions. You can inspect your installed version’s keyword list:
Example 10 — Inspecting Python keywords
import keyword
print(keyword.iskeyword("class"))
print(keyword.iskeyword("student_name"))
print("Keywords:", len(keyword.kwlist))
The first result is True, the second is False, and the number of keywords may vary with the Python version. This is a built-in standard-library module; no installation is needed.
5. Writing Readable, Well-Structured Python
5.1 Comments explain intent
A comment starts with # outside a string and normally extends to the end of that line. Python ignores it during execution. Use comments to explain why something is done, rather than narrating every obvious instruction.
Example 11 — Useful comments
order_total = 1200
# Offer free delivery on orders worth at least 1000.
if order_total >= 1000:
delivery_fee = 0
else:
delivery_fee = 60
print("Delivery fee:", delivery_fee)
5.2 Docstrings are documentation, not comments
A string placed as the first statement within a function, class or module can become its docstring. It explains purpose and is accessible programmatically. Triple-quoted strings used elsewhere are still strings; they should not be treated as a general replacement for comments.
Example 12 — A documented function
def calculate_square(number):
"""Return the square of a number."""
return number * number
print(calculate_square(6))
print(calculate_square.__doc__)
5.3 Meaningful blank lines and spacing
Separate logical sections with blank lines. Use a single space around most binary operators, such as =, + and >=, to improve readability. Avoid cramped or inconsistent spacing. For a small script, group configuration, calculations and output clearly.
5.4 Multi-line expressions
Long statements are easier to read when broken inside parentheses, brackets or braces. Prefer this implicit line continuation over backslash continuation.
Example 13 — Readable multi-line calculation
prices = [
149.50,
299.00,
450.25,
]
subtotal = sum(prices)
service_rate = 0.05
total = (
subtotal
+ subtotal * service_rate
)
print(f"Total: {total:.2f}")
There is no requirement to use a backslash when the expression is inside parentheses. Python automatically understands the logical statement continues.
5.5 A small, professional file layout
A simple script can begin with module documentation and imports, then constants, then functions, and finally a clear entry point. This pattern is especially useful as projects grow.
Example 14 — Complete script structure
"""A tiny example of an organized Python script."""
DEFAULT_GREETING = "Welcome to Smartyfy"
def greet(name):
"""Display a personalized welcome message."""
print(f"{DEFAULT_GREETING}, {name}!")
def main():
"""Run the application."""
greet("Learner")
if __name__ == "__main__":
main()
This script introduces two ideas you will study in more depth later: functions collect related behavior, and the if __name__ == "__main__": guard runs the entry point when the file is executed directly, while avoiding that automatic call during a normal import.
snake_case for variables and functions, UPPER_CASE for constants by convention, and CapWords for class names. These naming styles improve consistency in collaborative projects.6. Recognizing and Fixing Common Errors
Python error messages usually include the file location, line number and error type. Read the traceback from the relevant line and inspect nearby code. A missing character may be reported on the next line, so check the statement above when the highlighted line looks correct.
Issue A — Missing colon
Incorrect:
age = 20
if age >= 18
print("Adult")
This raises SyntaxError. Add a colon after the condition.
Correct:
age = 20
if age >= 18:
print("Adult")
Issue B — Missing indentation
Incorrect:
if True:
print("This line must be indented")
This raises IndentationError. The statement inside the block needs indentation.
Correct:
if True:
print("This line is indented")
Issue C — An undefined name
Incorrect:
item_count = 4
print(item_counts)
The name used by print() does not match the variable name. This normally raises NameError, not SyntaxError. Fix the spelling to print(item_count).
Issue D — Comparing versus assigning
= assigns a value; == compares two values. Confusing them changes or invalidates the statement.
status = "ready" # Assignment
print(status == "ready") # Comparison: True
Issue E — Mixing tabs and spaces
A source file can display aligned code while containing a mix of tab characters and spaces. Configure your editor to use four spaces and enable visible whitespace where possible. Reindent the affected block consistently.
Issue F — A missing closing quote or bracket
Incorrect: print("Hello) or values = [1, 2, 3.
Check that the opening and closing quotes and delimiters match. Many editors highlight matching pairs.
A reliable debugging workflow
- Read the full error message and note the file and line.
- Identify the error category: syntax, indentation, undefined name or incorrect behavior.
- Inspect the line and surrounding block for colons, quotes, brackets and indentation.
- Make one small change at a time.
- Rerun the program and verify the expected output.
- Retain a simple test case to prevent the same mistake from returning.
7. Guided Mini-Project — Professional Order Summary
Scenario: A small shop wants a readable Python script that calculates an order amount, applies a delivery fee only for smaller orders, prints a formatted receipt and keeps related behavior inside a function.
Step 1 — Define the rules
- Multiply item price by quantity to obtain a subtotal.
- If the subtotal is at least ₹1,000, delivery is free.
- Otherwise, delivery costs ₹60.
- Print the customer’s name, subtotal, delivery fee and grand total.
Step 2 — Write and run the full script
"""Create a simple, readable customer order summary."""
FREE_DELIVERY_THRESHOLD = 1000
STANDARD_DELIVERY_FEE = 60
def print_order_summary(customer_name, unit_price, quantity):
"""Calculate and print a customer's order total."""
subtotal = unit_price * quantity
if subtotal >= FREE_DELIVERY_THRESHOLD:
delivery_fee = 0
else:
delivery_fee = STANDARD_DELIVERY_FEE
grand_total = subtotal + delivery_fee
print("------ ORDER SUMMARY ------")
print("Customer:", customer_name)
print(f"Subtotal: ₹{subtotal:.2f}")
print(f"Delivery: ₹{delivery_fee:.2f}")
print(f"Total: ₹{grand_total:.2f}")
def main():
"""Run a demonstration order."""
print_order_summary("Asha", 299, 4)
if __name__ == "__main__":
main()
Expected output
Step 3 — Understand the structure
- Module docstring: briefly states the file’s purpose.
- Constants: name business rules clearly.
- Function definition: begins with
defand ends its header with a colon. - Indented body: groups calculation and display statements.
- if/else: selects the delivery fee while preserving aligned branch headers.
- Formatted output:
:.2fdisplays numeric values with two decimal places. - main guard: provides a recognizable program entry point.
Step 4 — Test the other branch
Change the call to print_order_summary("Ravi", 150, 2). The subtotal becomes ₹300, so delivery becomes ₹60 and the total becomes ₹360. Trace the indentation to explain why exactly one delivery branch executes.
8. Guided Practice, Exercises & Challenge
Guided practice A — Predict the output
number = 8
if number % 2 == 0:
print("Even")
else:
print("Odd")
print("Done")
Prediction: Which lines will print, and how many times? Then execute to verify.
View answer and explanation
The output is Even followed by Done. The condition is true because 8 has a remainder of zero when divided by 2. The final statement sits outside the conditional block.
Guided practice B — Repair the code
# Intentionally broken: do not copy as a working example.
user = "Maya"
if user == "Maya"
print("Welcome")
Add the required colon and indentation, then rerun it. Explain which correction addresses which error.
View corrected code
user = "Maya"
if user == "Maya":
print("Welcome")Independent exercises
1. Create variables named employee_name and employee_id; print both clearly.
Hint
Define each value before printing it.
Show answer and explanation
Labels make the two values easy to distinguish; the identifier remains a string if leading zeros are meaningful.
employee_name = "Asha"
employee_id = "0042"
print("Employee:", employee_name)
print("ID:", employee_id)2. Write an if/else block that checks whether an integer is positive or not positive.
Hint
Zero belongs to the not-positive branch.
Show answer and explanation
Use number > 0; positive means strictly greater than zero. Test 5, 0, and -2 to exercise both paths.
number = 0
if number > 0:
print("Positive")
else:
print("Not positive")3. Write a for loop that prints 1 through 5, followed by a single Finished message.
Hint
The final message must be outside the loop.
Show answer and explanation
range(1, 6) produces 1 through 5. Keeping Finished unindented relative to the loop body prints it once after all five iterations.
for number in range(1, 6):
print(number)
print("Finished")4. Write a list of three subjects across multiple lines inside square brackets.
Hint
Square brackets allow implicit continuation.
Show answer and explanation
The list has three string elements. The trailing comma is optional but makes later additions simple.
subjects = [
"Math",
"Science",
"Python",
]
print(subjects)5. Demonstrate the difference between price = 100 and price == 100.
Hint
Print the comparison result separately.
Show answer and explanation
Assignment binds 100 to price. The equality expression compares the current value without assigning a new one; its result here is True.
price = 100
print(price == 100)6. Write a small function with a one-line docstring and print a result.
Hint
Put the docstring first inside the function.
Show answer and explanation
The function returns the square and its docstring describes that result. Printing the call displays 36.
def square(number):
"""Return the square of number."""
return number * number
print(square(6))7. Intentionally misspell a variable name, note the error type, then fix it.
Hint
Trace the spelling of the assigned name.
Show answer and explanation
Assign item_count = 4, then deliberately try print(item_counts) in a fresh script. It raises NameError; fixing it to print(item_count) prints 4. Reload the browser page first if an earlier snippet happened to define the misspelled name.
8. Refactor a cramped code snippet into cleanly separated logical sections.
Hint
Separate setup, calculation, and display without changing the calculation.
Show answer and explanation
The total is 240. The grouped layout makes each stage visible and preserves the result of the original arithmetic.
unit_price = 80
quantity = 3
total = unit_price * quantity
print("Total:", total)Professional challenge — Attendance Checker
Write a small reusable function called show_attendance(name, attended, total). Calculate the attendance percentage. If the percentage is at least 75, print Eligible; otherwise print Below requirement. Use clean indentation, a docstring, descriptive names, a multi-line output if helpful, and a main() entry point. Assume total is greater than zero for this exercise.
Bonus: Test attendance values of 18/20 and 12/20. Explain how both code paths behave. In a later lesson, add validation for zero and negative totals.
Optional reference solution
def show_attendance(name, attended, total):
"""Display attendance percentage and eligibility."""
percentage = attended / total * 100
if percentage >= 75:
result = "Eligible"
else:
result = "Below requirement"
print(f"{name}: {percentage:.1f}% — {result}")
def main():
show_attendance("Anu", 18, 20)
show_attendance("Ravi", 12, 20)
if __name__ == "__main__":
main()
9. Knowledge Check
1. What is the difference between syntax and correct program logic?
Hint
Separate the grammar from the result.
Show answer and explanation
Python can parse total = price + quantity, but a bill requiring multiplication will still be wrong. Syntax checks grammar; tests and a clear requirement check behavior. Both are necessary.
2. What is Python’s recommended indentation style?
Hint
Use one consistent indentation unit.
Show answer and explanation
Use four spaces per indentation level. A colon introduces a suite and indentation identifies its body. Mixing tabs and spaces can cause errors or obscure which statements belong to a block.
3. What punctuation normally ends an if or def header?
Hint
The suite needs a visible boundary.
Show answer and explanation
Use a colon at the end of headers such as if ready: and def greet(name):, then indent the body. The colon and indentation work together; one does not replace the other.
4. Does student_name refer to the same variable as Student_Name?
Hint
Capitalization is part of the spelling.
Show answer and explanation
No. Python names are case-sensitive. Assigning student_name does not define Student_Name. Choose one spelling and use it consistently.
5. Can an identifier begin with a number?
Hint
Compare 2_students with students_2.
Show answer and explanation
No. Names may contain digits after the first character, for example students_2, but cannot begin with a digit. They also cannot be Python keywords.
6. What does # do outside of a string literal?
Hint
Check whether the character occurs inside quotes.
Show answer and explanation
Outside a string, # starts a comment that continues to the end of the line. Inside "#tag", it is ordinary string data. A comment explains code without executing as an instruction.
7. How does a docstring differ from an ordinary comment?
Hint
Consider what __doc__ exposes.
Show answer and explanation
A docstring is the first string statement of a module, class, or function and is available through __doc__. A normal # comment is ignored by the interpreter and is not that runtime documentation.
8. Why are parentheses useful for a long arithmetic expression?
Hint
Use grouping and implicit continuation together.
Show answer and explanation
Parentheses make intended arithmetic grouping clear and allow an expression to continue across lines without an explicit backslash. Grouping can change the result, so use it deliberately rather than for appearance alone.
9. What is the difference between = and ==?
Hint
One changes a binding; the other produces a comparison result.
Show answer and explanation
= assigns a value to a name. == compares two values for equality and normally returns a Boolean. To check a condition, compare; to store a result, assign.
10. What is the purpose of a main() entry-point pattern?
Hint
Distinguish importing definitions from starting the application.
Show answer and explanation
Define reusable functions separately, then call main() under if __name__ == "__main__":. Direct execution runs startup; ordinary import makes the definitions available without automatically starting the application.
10. Professional Checklist & Lesson Summary
Before marking this lesson complete, confirm that you can:
- Identify where one Python block begins and ends.
- Write an
if/elsestatement with a colon and four-space indentation. - Balance quotes, parentheses, brackets and braces.
- Distinguish naming rules from naming conventions.
- Fix a simple
SyntaxErrororIndentationError. - Organize a Python file using meaningful names, comments, functions and whitespace.
- Run the Order Summary project and independently modify its input values.
Key takeaway: Syntax makes a Python program executable; thoughtful structure makes it understandable, testable and maintainable. Strong professional habits begin with small scripts.
Next lesson: 005 — Variables and Naming Rules, where we will examine assignment, dynamic typing, object references, naming conventions and practical data-management examples in depth.
Smartyfy · Python Master Course V2 · Structured learning from fundamentals to advanced development and AI
Apply what you learned
Interactive self-check
Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.
This is a practice quiz. Results are saved on this browser when storage is available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.