Lesson · Getting Started
First Python Program
51 min readFirst Python Program
Your first program is small on purpose: the goal is to understand how source code becomes observable behavior. You will also learn to distinguish syntax errors from runtime failures.
Learning goals
- Run the same program as a saved
.pyfile and line by line in the interpreter, and name one behavioral difference between the two. - Explain what
print()does with its arguments, itssepandenddefaults, and what it returns. - Use
#comments for intent and say how a comment differs from a triple-quoted string that only looks like one. - Say how indentation changes parsing, and fix the
IndentationErrorthat inconsistent indentation raises. - Read a basic traceback: find the file, the line, and the exception type, and tell a
SyntaxErrorfrom a runtime failure.
Mental model
The split between the first two steps is the lesson's main diagnostic tool: a SyntaxError means parsing failed and nothing ran, while a traceback from a running program means the source parsed and execution stopped at the named line.
Mental model
read it top to bottom
source file ↓ parse: indentation and syntax must be valid statements executed top to bottom ↓ print() writes output as they run failure during execution reports a traceback
Core idea
A tiny program still has Python's two stages: the parser reads the whole file first, then the statements execute in order and produce output. print, comments, and indentation are the syntax that shapes what those stages see, and the difference between a syntax error and a runtime error follows directly from which stage failed.
print()
print() writes its arguments to standard output as a side effect, separated by sep and followed by end ("\n" by default), and returns None. The arguments are converted to str for display, and the objects themselves are not modified.
Comments
A comment starts with # outside any string literal and runs to the end of the line. The parser ignores it, so a comment documents the code for human readers and has no effect on runtime behavior.
Indentation
Indentation is part of Python's grammar: the spaces or tabs at the start of a line decide which block a statement belongs to. Statements in one block must be indented consistently, and an inconsistent block raises IndentationError before the program runs.
Statements
A statement is a unit of execution: assignment, import, def, if, return, or a bare expression all count. Statements run in order inside a script, and a statement cannot be dropped into an expression where a value is required.
Expressions
An expression is code that produces a value, from a lone literal like 2026 to a call like print(name) or an f-string. Expressions can appear inside statements, and the interactive interpreter displays their value automatically.
Running a script
Run a script by giving its path to the selected Python interpreter. The file executes top-level statements in order and normally uses __main__ as its module name.
Syntax errors
A SyntaxError means Python could not parse the source into a valid program. The code never reaches normal execution until the syntax is corrected.
Runtime errors
A runtime error occurs after valid source has started executing, usually as an exception such as TypeError, ValueError, or ZeroDivisionError.
Reading tracebacks at a basic level
A traceback shows the active call chain at the point an exception escaped. Start with the exception type and message, then inspect the nearest relevant application frame.
Walkthrough
- The two assignment statements bind
nameto thestr"Python" andyearto theint2026; nothing is printed yet, and the bindings are the program's whole state. - Each
print(f"...")call builds its argument first: the f-string substitutes{name}and{year}with the objects' text, thenprintwrites one line and supplies the newline through itsenddefault. printreturnsNone; assigning the call to a name would storeNone, not the text. The visible output is a side effect, not a return value.- Predict before running: the exact two lines of output, which line runs first, and what the f-string would show if
namewere never bound.
Experiments to try
- Add
print("Hello", "world")and thenprint("Hello", "world", sep="-"); explain where the space versus the dash comes from. - Change the last print to
print(f"Course year: {year}", end=" ")and addprint("done")after it; the two lines merge. Predict the exact output first. - Write
print(name, year)and compare it with the two f-string versions. Note which form still works when the text needs punctuation such as!next to the value. - Delete a closing quote to raise a
SyntaxError, then addprint(undefined_name)to raise a runtime error, and compare where each appears in the run.
Common mistakes
- Expecting
printto return the text it shows: the return value isNone, soresult = print("hi")bindsNoneand later use ofresultsurprises. - Treating
#comments and triple-quoted strings as the same thing: a string expression builds a real object at run time, while a comment is discarded at parse time. - Mixing tabs and spaces in one block: Python 3 raises
TabError, aSyntaxErrorsubclass, when one line's indentation is ambiguous relative to the others. - Reading only the last line of a traceback: the exception type matters, but the file and line above it say where the failure actually occurred.
Practice: Easy
- Type the worked example into
hello.pyby hand and run it; then rename both variables and confirm the output follows the new names. - Run the same lines in the interactive interpreter one at a time and note one thing the REPL echoes that the script does not.
- Comment out the second
printcall with#and rerun, then wrap the call in triple quotes instead. The output is the same, so explain what the triple-quoted version still creates as a statement.
Practice: Medium
- Extend the program with
name = input("Name: ")and run it twice, once with a name and once pressing Enter immediately; record both outputs. - Rewrite the two f-strings with
str.formatand with%formatting, run all three versions, keep the one you find most readable, and justify the choice in one sentence. - Produce one
SyntaxErrorand oneNameErroron purpose; explain which one stops the file before any output and which one lets earlier lines run first.
Practice: Hard
- Write
greet.pythat prints a three-line message built from at least two variables and one literal, with comments marking which line is which kind of statement. State the expected output before running. - Build the smallest program that prints one line and then fails with a traceback. Explain, step by step, how Python reached the failure and why the earlier
printstill appeared. - Compare the same five-line program saved as a file with the same lines pasted into the REPL: list three behaviors that differ, including echo, rerunning, and where errors appear.
Lesson checklist
- I can run the worked example as a file and in the interpreter and name one behavioral difference.
- I can explain what
printreturns and why the return value is not the visible text. - I can tell a
SyntaxErrorfrom a runtime error by the stage where it appears. - I can read the file, line, and exception type out of a simple traceback.
Remember
A first program shows the two stages to keep reasoning about: Python parses the whole file first, then executes statements in order and prints as it goes. `print` performs output as a side effect and returns `None`, comments are discarded at parse time, and indentation is grammar rather than decoration.
Interview angles
What is the main purpose of **print()**?+
print() converts its arguments to text, writes them to standard output separated by sep (a single space by default), finishes the line with end ("\n" by default), and returns None. Several objects can be printed in one call, and none of them are mutated.
What should you pay attention to when using **Comments**?+
A comment starts with # outside any string and runs to the end of the line. The parser discards it, so comments document intent for readers and never change what the program does or what objects exist at run time.
How does **Indentation** fit into this lesson?+
Indentation is part of Python's grammar: the spaces or tabs at the start of a line decide which block a statement belongs to. Statements in one block must be indented consistently, and an inconsistency raises IndentationError before the program runs.
Why does `result = print("hi")` not store the text shown on screen?+
print writes to standard output as a side effect and returns None, so the assignment binds result to None. To keep the text, build it as a string (result = "hi") and print that value separately.