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

Updated 2 Dec 20266 min read
Python Syntax Basics: Rules, Worked Examples and Exam-Style Traps

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.

python
score = 72

if score >= 60:
    result = "pass"
    print(result)

print("checked")
Code
pass
checked

Both 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.

Indentation map of a Python score check, showing score 72, result pass, and outputs pass and checked, alongside an invalid missing-colon header.

2. Names, literals and assignment build Python state

These assignments create a compact state whose types matter later:

Statement

Bound value

Type

student_name = "Asha"

"Asha"

string

attempts = 3

3

integer

accuracy = 0.875

0.875

floating point

qualified = True

True

Boolean

subjects = ["Python", "DSA"]

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

17 / 5

3.4

17 // 5

3

17 % 5

2

2 ** 3

8

5 + 2 * 3

11

(5 + 2) * 3

21

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:

python
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

adjusted >= 65

total after iteration

passed after iteration

1

64

68

True

0 -> 68

0 -> 1

2

71

75

True

68 -> 143

1 -> 2

3

58

62

False

143

2

The final calculation is average = total / passed = 143 / 2 = 71.5, so the exact output is:

Code
143 2 71.5

Square 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.

Left-to-right execution trace of a marks loop, showing totals 68, 143, 143, final average 71.5, and output 143 2 71.5.

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.

python
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

if score >= 60

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

if score = 72:

SyntaxError: assignment is not a comparison

Write if score == 72:

student-name = "Asha"

The hyphen is parsed as subtraction, so the assignment is rejected

Write student_name = "Asha"

Class = "Python", then reading class

class is a reserved keyword; Class is a different valid name

Choose a descriptive non-keyword name

print("Python)

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.

  1. Valid identifiers among student_score, 2score, class and _attempts: student_score and _attempts.

  2. 17 // 5 + 17 % 5: 3 + 2 = 5.

  3. Worked-program output: 143 2 71.5.

  4. Is print(10 / 0) a syntax error? No; it is accepted and fails at runtime.

Another rebinding trace:

python
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.