Unit 1: Setting up your Programming Environment; Variables, Expression and Statements
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.pyis executed by the commandpython 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.pyfile, 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,totalandTOTALare 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.
printbecame a function,print("hi"), and division changed:3 / 2gives1.5in Python 3 but1in 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'sraw_input()was renamedinput(), and Python 2's evaluatinginput()was removed.- f-strings (3.6+):
f"Total = {total}"is now the standard formatting style.
- Strings are Unicode by default: text handling no longer needs the
- Checking your version: run
python --version(orpython -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,
cmdreports'python' is not recognized as an internal or external command. - What gets installed: the interpreter
python.exe, the package managerpip, and IDLE, a simple editor-plus-shell bundled with Python. - The
pylauncher: Windows-only;py -3.11 script.pyselects 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
.pyfile is only text. Word processors must be avoided because they insert formatting bytes. - Installing libraries:
pip install numpyfrom the command prompt fetches from PyPI.pip listshows what is present. - Common Windows pitfall: file paths use backslashes, which are escape characters in strings. Write
"C:\\data\\file.txt"orr"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.
>>> 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 runpython hello.pyfrom the folder containing it.
# hello.py — my first program
print("Hello, World!")- Why the quotes matter:
Hello, World!without quotes is read as names and produces aSyntaxError; 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 1followed byNameError: 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 = 17means "letnrefer to 17".17 = nis aSyntaxError. - Rebinding:
n = 17followed byn = "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, 4binds both at once;a = b = 0binds both names to the same value. - Naming conventions (PEP 8):
lower_case_with_underscoresfor variables and functions,ALL_CAPSfor constants,CamelCasefor classes. Names should describe content —student_count, notsc. - Practical guidance: prefer short but descriptive names, avoid the single characters
l,OandIbecause they resemble digits, and use singular/plural to signal one item versus a collection (namevsnames).
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"thenprint(message)→NameError: name 'message' is not defined. - Wrong case: assigning
Totaland readingtotal. - Use before assignment:
print(count)placed abovecount = 0. - Missing quotes on text:
city = DelhitreatsDelhias a variable name.
- Misspelling:
- 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.
SyntaxErrordiffers — 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), andNoneType(None). - Inspecting the type:
type(17)→<class 'int'>;type("17")→<class 'str'>. - Type governs behaviour:
'2' + '3'gives'23'(concatenation) while2 + 3gives5(addition). Mixing them,2 + '3', raisesTypeError. - Conversion functions:
int("42")→42,float("3.5")→3.5,str(42)→'42',int(3.9)→3(truncates toward zero). - Notation traps:
1,000,000is not an integer but a tuple of three values; leading zeros as in09are 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_2is valid,2moreis 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, includingFalse,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)— andkeyword.iskeyword("for")returnsTrue. - Shadowing built-ins:
list = [1, 2]orstr = "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 + 1is an expression;x = x + 1andprint(x)are statements. A bare value like42is also a legal expression statement. - Interactive vs script behaviour: at the
>>>prompt,x + 1displays 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 inif,for,def) introduce an indented block. printdetails:print("a", "b")inserts a space separator and a trailing newline;sepandendchange both, as inprint("a", "b", sep="-", end="").
B. Operators and operands
Operators are symbols representing computation; operands are the values they act on.
- Arithmetic:
+,-,*,/(true division, alwaysfloat),//(floor division),%(modulus/remainder),**(exponentiation). - Concrete values:
7 / 2→3.5;7 // 2→3;-7 // 2→-4(floors);7 % 2→1;2 ** 10→1024. - Uses of
%:n % 2 == 0tests evenness;n % 10extracts the last decimal digit;minutes % 60converts a total into a remainder. - Comparison operators return
bool:==,!=,<,>,<=,>=. Note==compares,=assigns. - Logical operators:
and,or,not, evaluated lazily —orstops at the first true operand. - Augmented assignment:
x += 1is shorthand forx = 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 →not→and→or. - Associativity: most operators are left-to-right, so
9 - 3 - 2is4; exponentiation is right-to-left, so2 ** 3 ** 2is512, not64. - Same-level operators:
*and/share a level, so6 / 2 * 3evaluates left to right as9.0. - Worked example:
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) * 4→20. 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
*:"-" * 20draws 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"raisesTypeError. - 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"raisesTypeError; 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 s→True. - 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: ")) + 1composes a call inside a call inside arithmetic. - Function calls are expressions:
len("hello") * 2→10, becauselen(...)yields anintusable as an operand. - The limit: the left side of an assignment must be a name, not an expression —
minute * 60 = hoursis aSyntaxError. - 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 secondsis useful;# add 1 to iis noise that duplicates the code. - Docstrings differ: a
"""..."""string as the first statement of a module or function is a retained object accessible viahelp(), not a discarded comment. - Debugging use: temporarily commenting out a line isolates the source of an error without deleting work.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →