Python Syntax Basics: Rules, Worked Examples and Exam-Style Traps
Learn how Python reads names, expressions and indented blocks. Then trace a complete marks program and repair the syntax mistakes beginners often make.
KnowledgeGate Team
Exam prep & CS education

Python looks readable until one missing colon, one wrongly indented line or one use of = where == was intended stops the program or changes its meaning. Compare score = 72, which assigns a value, with score >= 60, which compares two values. Syntax is not punctuation memorisation; it is the structure through which Python knows the intended operation and block. Names, values, indentation, operators and block-forming statements give Python that structure; the example then traces marks [64, 71, 58] with bonus 4 and threshold 65.
1. What Python syntax controls: tokens, statements and indented suites
Syntax supplies the structural rules for parsing source code. total = 3 + 4 is valid and evaluates to 7. total = unknown + 4 is also valid syntax, but execution fails because unknown is unbound. Parser errors prevent startup; runtime errors follow accepted syntax.
The units include identifiers such as score, literals such as 72 and "pass", operators such as >=, statements such as score = 72, and suites introduced by a colon and indentation.
score = 72
if score >= 60:
result = "pass"
print(result)
print("checked")pass
checkedBoth indented statements belong to the if; the dedented final print runs afterwards. if score >= 60 needs a colon, and its first statement needs indentation. Use four spaces without mixing tabs and spaces.
Start with Introduction to Python: Core Concepts, Worked Trace and Exam Patterns for the broader path through types, operators, control flow, functions and alias mutation. This page stays at the parser boundary: token classes, valid statements, suite indentation, and the distinction between parser rejection and code that is accepted before failing at runtime. Coding & DSA Courses for Placements connects these foundations to Python, other languages and problem-solving.

2. Names, literals and assignment build Python state
These assignments create a compact state whose types matter later:
Statement | Bound value | Type |
|---|---|---|
|
| string |
|
| integer |
|
| floating point |
|
| Boolean |
| two items | list |
Names are case-sensitive: qualified and Qualified differ. student_score and _attempts are valid; 2score begins with a digit and class is reserved.
Assignment and equality differ. score = 72 binds; score == 72 evaluates to True without rebinding. score = score + 5 reads 72, computes 77, then rebinds score; score += 5 gives this integer the same update.
After left, right = 7, 11, left, right = right, left evaluates the right side first, leaving left = 11 and right = 7. Outside strings, # starts a comment, so attempts = 3 # allowed attempts binds 3.
3. Operators and expression order: compute before you code
Small operator changes can produce sharply different results:
Expression | Result |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Parentheses show grouping. With score = 72 and attempts = 2, score >= 60 and attempts <= 3 is True; attempts = 4 makes it False. The related qualified = score >= 60 and attempts <= 3, retry = score < 60 or attempts > 3, and not qualified demonstrate and, or and not.
60 <= score < 80 is True for score = 72 because both bounds hold. Distinguish = from ==, and parenthesise mixed expressions.
4. Fully worked Python trace: bonus marks, threshold and average
Trace this complete program:
marks = [64, 71, 58]
bonus = 4
total = 0
passed = 0
for mark in marks:
adjusted = mark + bonus
if adjusted >= 65:
total += adjusted
passed += 1
average = total / passed
print(total, passed, average)iteration | mark | adjusted |
| total after iteration | passed after iteration |
|---|---|---|---|---|---|
1 | 64 | 68 |
|
|
|
2 | 71 | 75 |
|
|
|
3 | 58 | 62 |
|
|
|
The final calculation is average = total / passed = 143 / 2 = 71.5, so the exact output is:
143 2 71.5Square brackets form the list. The for header ends in a colon, its suite is indented once and the nested if twice. += updates accumulators; dedented statements run after the loop.
Division is safe because passed = 2. With no qualifying mark, passed = 0, so division causes a runtime error, not a syntax error.

5. Conditions, loops and functions reuse the same block grammar
The if, for and def headers end with a colon and own indented suites. return ends the call with a result; print displays a representation and cannot replace return.
def adjusted_average(marks, bonus, threshold):
total = 0
passed = 0
for mark in marks:
adjusted = mark + bonus
if adjusted >= threshold:
total += adjusted
passed += 1
return total / passed if passed else 0.0
result = adjusted_average([64, 71, 58], 4, 65)
print(result)The output is 71.5: passed = 2, so the function returns 143 / 2. adjusted_average([20, 30], 4, 65) leaves passed = 0; the guard returns 0.0 instead of dividing by zero. Parameters are local.
Fibonacci, prime and GCD programs apply conditions, loops and functions.
6. Common Python syntax traps and exact repairs
Use the error phase and proposed repair to diagnose each mistake:
Mistake | What happens | Repair |
|---|---|---|
| SyntaxError before execution | Add the colon: if score >= 60: |
No indentation after a block header | IndentationError before execution | Indent the suite consistently |
Inconsistent tabs and spaces in one suite | TabError or unintended nesting | Use four spaces consistently |
| SyntaxError: assignment is not a comparison | Write if score == 72: |
| The hyphen is parsed as subtraction, so the assignment is rejected | Write student_name = "Asha" |
| class is a reserved keyword; Class is a different valid name | Choose a descriptive non-keyword name |
| SyntaxError: unterminated string literal | Close with the matching quote |
if score = 72: is invalid syntax. print(name) is valid but fails at runtime if name is unbound. print(10 / 0) likewise fails during execution.
Indentation can change meaning without breaking syntax. Version A keeps both updates inside the if, producing (143, 2). Version B dedents passed += 1 to the loop, producing (143, 3); 143 / 3 is approximately 47.6667.
After mastering these statements, use Python Output-Based Questions: 13 Solved Snippets for aliasing, copies, slicing and mutability.
7. How exam-style and interview-style questions probe syntax
Syntax questions usually reduce to four checks: identifier validity, operator evaluation, execution phase and exact output.
Valid identifiers among
student_score,2score,classand_attempts:student_scoreand_attempts.17 // 5 + 17 % 5:3 + 2 = 5.Worked-program output:
143 2 71.5.Is
print(10 / 0)a syntax error? No; it is accepted and fails at runtime.
Another rebinding trace:
x = 3
y = x
x += 2
print(x, y)The answer is 5 3. y was bound to the integer before x was rebound by += 2; mutable objects need separate reasoning.
Why does version B calculate 143 / 3, not 143 / 2? Dedented passed += 1 runs every iteration, including failed 62 >= 65, testing block structure and arithmetic.
8. Python syntax basics: the short version and next step
Keep this six-line checklist:
Names are case-sensitive.
=binds, while==compares.A colon introduces a compound statement's suite.
Indentation defines membership in that suite.
Parentheses make expression grouping explicit.
Valid syntax can still fail at runtime.
Worked result: adjusted marks 68, 75, 62, qualifying total 143, count 2, average 71.5.
Keep marks [64, 71, 58] and threshold 65, but change bonus from 4 to 6. Predict: adjusted marks [70, 77, 64], total 147, passed 2, average 73.5, output 147 2 73.5.
Use the Python Course: Concepts, MCQs & Coding for a structured sequence. When variables, conditions, loops and functions are comfortable, apply them with DSA Using Python.
Keep learning
Python Data Types Explained: Concepts, Conversions and Exam-Style Output Tracing
Learn how Python names, objects and built-in types work, then trace conversions, division, list aliasing and shallow copying through an exact program.
Decorators in Python: @ Syntax, Wrappers and Worked Examples
Understand when decoration happens, what a wrapper receives, and how return values travel back. Runnable examples cover parameters, stacking and built-ins.
Introduction to Python: Syntax, Execution and Worked Examples
Build a reliable Python mental model, then trace values, branches, loops, aliases and a five-score function without skipping a state change.
Python Dictionaries Tutorial: Syntax, Methods and Worked Examples
Learn how Python dictionaries store, retrieve and transform key-value data through runnable examples, common traps and one complete marks-processing task.





