Skip to content
Print & Expression Statements
step 1/3

Reading — step 1 of 3

From Expressions to Statements

~2 min readStatements & State

Print & Expression Statements

Up to now, our language only evaluates single expressions. Real programs are sequences of statements — actions that produce side effects (printing, variable assignment, control flow) rather than just computing values.

Expressions vs Statements

An expression produces a value: 1 + 2 evaluates to 3. A statement does something: print 3; outputs 3 to the console. The semicolon ; terminates a statement, just like in C, Java, and JavaScript.

Two Statement Types

Print Statement

print <expression>;

Evaluates the expression and outputs the result followed by a newline. print is a built-in keyword, not a function call (we have not implemented functions yet).

Expression Statement

<expression>;

Evaluates the expression and discards the result. This is useful for side effects once we add function calls: doSomething(); calls a function but ignores its return value.

Parsing Statements

The parser now processes a program — a list of statements until EOF:

program    → statement* EOF
statement  → printStmt | exprStmt
printStmt  → "print" expression ";"
exprStmt   → expression ";"

The key change: parse() no longer returns a single expression. It returns a list of statements.

Executing Statements

The interpreter gains an execute() method for statements:

execute(stmt):
    if stmt is Print:
        value = evaluate(stmt.expression)
        output(stringify(value))
    if stmt is Expression:
        evaluate(stmt.expression)  // discard result

Stringification

When printing values, we need to convert them to human-readable strings:

  • Numbers: 42.0 should print as 42 (drop .0 for integers), 3.14 as 3.14
  • Strings: print without quotes
  • Booleans: true or false
  • Nil: nil

Python's repr() vs str() distinction is relevant here — print uses str() for human-readable output, while repr() shows the programmer-facing representation.

Your Task

Add statement parsing and execution. A program is now a sequence of print and expression statements, each terminated by a semicolon.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…