Unit 1: Setting up your Programming Environment; Variables, Expression and Statements

INT108 — Python Programming 11 min read

I. Orientation: Python and the Interpreted Model

Python was created by Guido van Rossum at CWI in the Netherlands and first released in February 1991. It is a high-level, general-purpose language that runs through an interpreter — the program python reads your source text, compiles it to bytecode, and executes it on the Python Virtual Machine. Because there is no separate manual compile step, you can either run a saved script file or type statements one at a time and see results immediately.

Defining properties that the rest of the unit depends on:

  • Interpreted, not compiled to machine code: the file hello.py is executed by the command python hello.py; errors surface at run time, in the order the lines execute.
  • Two modes of use: interactive mode (the >>> prompt, which echoes the value of every expression) and script mode (a .py file, which prints only what you tell it to print).
  • Dynamically typed: a variable has no declared type. The value carries the type, and the same name may later refer to a value of a different type.
  • Everything is an object: integers, strings and functions alike have a type, retrievable with type(x).
  • Indentation is syntax: leading whitespace defines blocks, replacing braces. The convention is four spaces per level.
  • Case-sensitive: Total, total and TOTAL are three distinct names.

II. Setting up the Programming Environment

Choosing an interpreter and getting the first program to run

A. Python versions

Version choice matters because Python 3 is not backward-compatible with Python 2.

  • Python 2 (2.0 in 2000; 2.7 final release): end-of-life 1 January 2020, no longer maintained or patched. Recognisable by print "hi" as a statement.
  • Python 3 (3.0 in December 2008): the only version for new work. print became a function, print("hi"), and division changed: 3 / 2 gives 1.5 in Python 3 but 1 in Python 2.
  • Other Python 3 changes worth knowing:
    • Strings are Unicode by default: text handling no longer needs the u"..." prefix.
    • input() returns a string: Python 2's raw_input() was renamed input(), and Python 2's evaluating input() was removed.
    • f-strings (3.6+): f"Total = {total}" is now the standard formatting style.
  • Checking your version: run python --version (or python -V) at the command prompt; inside a program, import sys; print(sys.version).
  • Implementations vs versions: CPython is the reference implementation written in C; Jython (JVM), IronPython (.NET) and PyPy (JIT-compiled) run the same language differently.

B. Python on Windows

Windows does not ship with Python, so it must be installed and put on the search path.

  • Installer: download the Windows 64-bit installer from python.org, and on the first screen tick "Add python.exe to PATH". Without it, cmd reports 'python' is not recognized as an internal or external command.
  • What gets installed: the interpreter python.exe, the package manager pip, and IDLE, a simple editor-plus-shell bundled with Python.
  • The py launcher: Windows-only; py -3.11 script.py selects a specific installed version when several coexist.
  • Editors and IDEs: IDLE for beginners, VS Code with the Python extension, or PyCharm. Any plain-text editor works — a .py file is only text. Word processors must be avoided because they insert formatting bytes.
  • Installing libraries: pip install numpy from the command prompt fetches from PyPI. pip list shows what is present.
  • Common Windows pitfall: file paths use backslashes, which are escape characters in strings. Write "C:\\data\\file.txt" or r"C:\data\file.txt".

C. Running a 'Hello World' program

The traditional first program confirms that the interpreter, the editor and the path all work together.

  • Interactive mode: open a terminal, type python, and at the >>> prompt enter the call directly.
PYTHON
>>> print("Hello, World!")
Hello, World!
>>> 2 + 3          # the prompt echoes expression values automatically
5
>>> exit()         # or Ctrl-Z then Enter on Windows
  • Script mode: save the following as hello.py, then run python hello.py from the folder containing it.
PYTHON
# hello.py — my first program
print("Hello, World!")
  • Why the quotes matter: Hello, World! without quotes is read as names and produces a SyntaxError; inside quotes it is a string value.
  • Reading a traceback: an error report names the file, the line number and the error type — for example File "hello.py", line 1 followed by NameError: name 'prnt' is not defined. Read the last line first; it states what went wrong.
  • Three classes of error: syntax errors (the code cannot be parsed), runtime errors or exceptions (parsing succeeds, execution fails), and semantic errors (it runs, but does the wrong thing).

III. Variables, Values and Types

Names, the objects they refer to, and the rules that constrain both

A. Naming and using variables

A variable is a name bound to a value by the assignment operator =, which is read right-to-left: evaluate the right side, attach the name on the left to the result.

  • Assignment is not equality: n = 17 means "let n refer to 17". 17 = n is a SyntaxError.
  • Rebinding: n = 17 followed by n = "cat" is legal; the name now refers to a string. The old value is discarded if nothing else refers to it.
  • Multiple assignment: x, y = 3, 4 binds both at once; a = b = 0 binds both names to the same value.
  • Naming conventions (PEP 8): lower_case_with_underscores for variables and functions, ALL_CAPS for constants, CamelCase for classes. Names should describe content — student_count, not sc.
  • Practical guidance: prefer short but descriptive names, avoid the single characters l, O and I because they resemble digits, and use singular/plural to signal one item versus a collection (name vs names).

B. Avoiding NameError when using variables

A NameError is raised when Python evaluates a name that has never been bound.

  • The rule: a variable must be assigned before it is used, in execution order — not merely somewhere in the file.
  • Typical causes:
    • Misspelling: mesage = "hi" then print(message)NameError: name 'message' is not defined.
    • Wrong case: assigning Total and reading total.
    • Use before assignment: print(count) placed above count = 0.
    • Missing quotes on text: city = Delhi treats Delhi as a variable name.
  • How to fix: read the last line of the traceback for the offending name, check spelling and capitalisation against the assignment, and confirm the assignment executes first. SyntaxError differs — it is reported before anything runs at all.

C. Values and types

A value is a basic unit of data; its type determines what operations are permitted.

  • Core built-in types: int (17), float (3.2), str ('Hello'), bool (True/False), and NoneType (None).
  • Inspecting the type: type(17)<class 'int'>; type("17")<class 'str'>.
  • Type governs behaviour: '2' + '3' gives '23' (concatenation) while 2 + 3 gives 5 (addition). Mixing them, 2 + '3', raises TypeError.
  • Conversion functions: int("42")42, float("3.5")3.5, str(42)'42', int(3.9)3 (truncates toward zero).
  • Notation traps: 1,000,000 is not an integer but a tuple of three values; leading zeros as in 09 are a syntax error.

D. Variables, variable names and keywords

Identifier rules are enforced by the parser, and a small reserved vocabulary is off-limits.

  • Legal identifiers: any length; letters, digits and underscore only; must not begin with a digit. more_2 is valid, 2more is not, more@ is not.
  • Leading underscore: legal but conventionally signals an internal or private name.
  • Keywords are reserved: using one as a variable name is a syntax error, e.g. class = "X" fails. Python 3 has 35 keywords, including False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
  • Listing them at runtime: import keyword; print(keyword.kwlist) — and keyword.iskeyword("for") returns True.
  • Shadowing built-ins: list = [1, 2] or str = "x" is legal but destroys the built-in function for the rest of the program; avoid it.

IV. Expressions and Statements

How Python evaluates combinations of values and how it acts on them

A. Statements

A statement is a unit of code the interpreter can execute; an expression is a combination of values, variables and operators that evaluates to a value.

  • Expressions have values, statements have effects: x + 1 is an expression; x = x + 1 and print(x) are statements. A bare value like 42 is also a legal expression statement.
  • Interactive vs script behaviour: at the >>> prompt, x + 1 displays the result; in a script the value is computed and thrown away unless printed.
  • One statement per line: the newline terminates a statement. \ at the end of a line, or an unclosed bracket, continues it. A semicolon can join two statements on one line but is discouraged.
  • Compound statements: headers ending in : (as in if, for, def) introduce an indented block.
  • print details: print("a", "b") inserts a space separator and a trailing newline; sep and end change both, as in print("a", "b", sep="-", end="").

B. Operators and operands

Operators are symbols representing computation; operands are the values they act on.

  • Arithmetic: +, -, *, / (true division, always float), // (floor division), % (modulus/remainder), ** (exponentiation).
  • Concrete values: 7 / 23.5; 7 // 23; -7 // 2-4 (floors); 7 % 21; 2 ** 101024.
  • Uses of %: n % 2 == 0 tests evenness; n % 10 extracts the last decimal digit; minutes % 60 converts a total into a remainder.
  • Comparison operators return bool: ==, !=, <, >, <=, >=. Note == compares, = assigns.
  • Logical operators: and, or, not, evaluated lazily — or stops at the first true operand.
  • Augmented assignment: x += 1 is shorthand for x = x + 1; *=, -=, //= follow the same pattern.

C. Order of operations

When several operators appear in one expression, precedence and associativity fix the order — remembered as PEMDAS.

  • Highest to lowest: parentheses → exponentiation → unary +/-*, /, //, %+, - → comparisons → notandor.
  • Associativity: most operators are left-to-right, so 9 - 3 - 2 is 4; exponentiation is right-to-left, so 2 ** 3 ** 2 is 512, not 64.
  • Same-level operators: * and / share a level, so 6 / 2 * 3 evaluates left to right as 9.0.
  • Worked example:
PYTHON
2 + 3 * 4 ** 2 / 8      # step 1: 4 ** 2  -> 16
                        # step 2: 3 * 16  -> 48
                        # step 3: 48 / 8  -> 6.0
                        # step 4: 2 + 6.0 -> 8.0
  • Use parentheses for clarity: (2 + 3) * 420. Even when redundant, they document intent.

D. Operations on strings

Strings support a small set of operators plus a large set of methods; unlike numbers they are ordered sequences of characters.

  • Concatenation with +: "Hello" + " " + "World"'Hello World'. Both operands must be strings, so "Total: " + str(5) is needed.
  • Repetition with *: "-" * 20 draws a rule of twenty hyphens; "ab" * 3'ababab'. One operand must be an integer.
  • Illegal operations: -, / and %-as-arithmetic are undefined on strings; "15" - "2" raises TypeError.
  • Indexing and slicing: with s = "Python", s[0]'P', s[-1]'n', s[0:3]'Pyt' (the end index is excluded), s[2:]'thon'.
  • Immutability: s[0] = "J" raises TypeError; build a new string instead, "J" + s[1:].
  • Common methods and functions: len(s)6, s.upper()'PYTHON', s.lower(), s.strip() removes surrounding whitespace, s.replace("Py", "My"), s.split(), and the membership test "th" in sTrue.
  • Quoting: '...' and "..." are equivalent; """...""" spans lines. Escapes include \n (newline), \t (tab), \\ (backslash) and \".

E. Composition and comments

These two habits govern how expressions are built up and how the code is explained.

1. Composition

  • The principle: anywhere a value of the right type is allowed, an arbitrarily complex expression of that type may be substituted.
  • Nesting expressions: print("Average:", (a + b + c) / 3) composes arithmetic inside a function call; int(input("Enter age: ")) + 1 composes a call inside a call inside arithmetic.
  • Function calls are expressions: len("hello") * 210, because len(...) yields an int usable as an operand.
  • The limit: the left side of an assignment must be a name, not an expression — minute * 60 = hours is a SyntaxError.
  • Readability caution: deeply composed one-liners are legal but hard to debug; break them into intermediate named steps when the logic matters.

2. Comments

  • Syntax: # begins a comment; everything to end of line is ignored by the interpreter. Python has no block-comment marker, so each line needs its own #.
  • Placement: on its own line above the code it describes, or inline after at least two spaces — v = 5 # velocity in m/s.
  • Explain why, not what: # convert to seconds because the API expects seconds is useful; # add 1 to i is noise that duplicates the code.
  • Docstrings differ: a """...""" string as the first statement of a module or function is a retained object accessible via help(), not a discarded comment.
  • Debugging use: temporarily commenting out a line isolates the source of an error without deleting work.