Formal Languages
‣ Strict syntax and grammar: Constructs
• Unambiguous meaning (as opposed to natural language)
‣ Statements (An imperative program is a sequence of statements)
• Instruction to “do something”
Interpreted or Compiled
‣ Variables and Values (objects)
• Have type (only certain operations on defined on objects of each type)
same name in different name-
‣ Names (in a name-space ‘set of names’)
spaces mean different things
• Reserved keywords, Module/Library, Function, Variable, Type and Class
‣ Literals
Python Review
‣ Objects and their names
‣ Actions Assignment Arith. op. Relational op. Logical op.
• Operators: = ** * / // % + — Aop= < > <= >= == != not and or
Operator Precedence
Type Operators
High **
Arithmetic *, /, //, %
+,-
Relation ==, !=, <=, >=, >, <
not
Logical
Low and
or
Python Review
‣ Objects and their names
‣ Actions Assignment Arith. op. Relational op. Logical op.
• Operators: = ** * / // % + — Aop= < > <= >= == != not and or
Function parameters
‣ Control flow
Precedence String
Tuple List maker
• if/elif/else <condition>: logical expression
Ordinal item
ent
• while <condition>: ( ) [ ] , . : ' " #
comm
if/loop
• for v in <iterable>: e.g., range(start, num, step) slice
Decimal def
• Functions (def, return, call) Name’s context
- Built-in: abs, len, print, input, open, readline, readlines, write, join, append, strip
writelines, close, split ..
‣ Reserved words: import, True, None, with, as, False ..
Python Overview
‣ Commands are interpreted one by one (to produce bytecode)
• Bytecode executed by a runtime (Python executable)
‣ Shell environment for typing, interpreting, and executing
• Also run directly from a file (like passing all commands to a shell)
Can give multiple names
‣ Commands are actions on objects to the same object
one name only refers to one
• We refer to objects by name (aka variable) object (in any namespace)
‣ Objects are scalar or collection, mutable or immutable
‣ Objects have a type (or class) Type of an object determines what
actions are possible on them Some inter-type
Python is dynamically typed
conversion possible
Common Errors Reported Error
‣ Translation-time error Look out
• Syntax error: unrecognizable words, malformed constructs and paragraphs
- ((unmatched), a ++ b, missing ‘:’ ..
- Wrong indentation
• Semantic error:
- Wrong operation or type
- Uninitialized/Unavailable name used (mispelt?)
- Wrong number of operands/partameters used
‣ Run-time error:
• Unsupported/Unexpected operations (Exceptions) …
Common Errors Unreported Errors
‣ Program-logic error Look out for hidden assumptions
• Incorrect algorithm (or its coding) Debug incrementally, test each change
- Produces the wrong answer (sometimes or every time)
• Examples:
- Used unintended or improperly initialized variables (copy-paste?)
- Incorrect operator applied (relational, logical, indexing)
- Misunderstood order of evaluation (precedence, associativity of operators)
- Incorrect loop conditions (continuation/termination) or nesting
- Misunderstood what a function does, or how to control its operations
Objects, Operations, Names Python Review
‣ Operations work on a number of objects (operands), producing an object (result)
• Multiple operations can be combined in an expression
‣ Objects have type (class) int, bool, float, str, list .. see built-in function: type(..)
• Types determine the operations that they can be operands for
• Operations produce object is of a certain type
‣ Type conversion is possible for compatible types (Explicit/Implicit casting)
‣ Objects may have name (variable), by which they may be referred to
• Consist of letters, numbers and underscore; do not begin with a digit
• Can also be literal (constant) 5 6. 333.555 '333.555' None [5, 6]
Encapsulation, Scope, Name-space def f(x):
Python Review
x=x+1
‣ Encapsulation y = x*x
return x+y
• Module, Function, Class
x=y=3
• Modules and class can expose names in their name-space,
print(f(x), x)
Functions do not
• Names issued inside a function have life only inside the function see global
Encapsulation, Scope, Name-space Python Review
‣ Encapsulation
• Module, Function, Class
• Modules and class can expose names in their name-space, Functions do not
• Names issued inside a function have life only inside the function see global
‣ Importing a module allows the module name to become known
• Access names exposed by the module through module’s reference
module_ref.name
‣ Objects may consist of many sub-objects
• Which have names accessible through objects’s reference
object_ref.subobject_ref
Modules & Packages Python Review
‣ Module is a collection for names: import to use those names import time
‣ Names defined in module accessed by name-space qualification time.time()
‣ Can also import names directly from time import time
time()
• and give it a new name import time as builtin_time
builtin_time.time()
‣ <name_of_module> resides in file ‘name_of_module.py’
PYTHONPATH shell variable
• File ‘name_of_module.py’ is in ‘path’
sys.path.append(..)
‣ Many modules can be ‘packaged’ together
• Module files are placed in a directory with the same name as the package’s
• Entire package can be imported, or its modules from email import parser
from email.parser import Parser
Modules & Packages Python Review
mod.py
x=x+1
y = x*x import mod
def f():
print(y)
if __name__ == '__main__':
f()
Name Assignment Python Review
‣ RHS produces an object
‣ LHS is a reference (may contain an expression that generates references)
name1 is a name/reference
object1 may be literal or a reference
‣ name1 = object1 Give that object a(nother) name: name1
‣ [nam1, nam2] = [object1, object2]
Multiple assignments —
‣ (nam1, nam2) = [object1, object2] Unpack collection
‣ list1[3] = object1 list1 is a name, list1[3] is a reference
This reference will refer to this object now
Collection of Objects built-in function len(..) Python Review
membership test: in
‣ list: mutable, ordinal
.append(item), +list2
• x = [1, '3', 4.0, 5]
.insert(index, item), .remove(item), .pop(index)
‣ tuple: immutable, ordinal
return None
• x = (1, '3', 4.0, 5) +tup2 .index(item), .count(item)
‣ set: mutable, non-ordinal, non-indexable, has unique immutable items
• x = {1, '3', 4.0, 5} .add(item), .update({…}), |set2, &set2,
‣ dictionary: mutable, non-ordinal, indexable with key (needs unique keys)
• x = {'a': 122, 3: 778, 4.0: 'dish', 5: 77} .update(dict2), .pop(key), |dict2
.items(), .keys(), .values()
‣ string: immutable, ordinal
String Python Review
‣ Enclosed in single or double quotes
• ‘name1’ 'name2' "name3"
‣ Immutable collection, Ordinal (Iterable) '\u20B9 {} and {} paise only'.format(99, 0)
• 'name2'[3], for ch in 'name2' '\u20B9 {0} and {1} paise only'.format(99, 0)
‣ Operations '\u20B9 {x} and {y:.2f} paise only'.format(x=99, y=0)
• relational ops, 'name2' + "name2", 'name2'*2, print(f'Hello {name}')
‣ string is a class with internal functions exposing its namespace:
• s = 'qwerty schmerty '
• s.split(' '), s.strip('q '), s.find('rt', 4), s.upper(), s.isupper(), .format(..)
input(..) and print(..) Python Review
‣ input('prompt string')
• Receive string of keyboard-typed characters until a “Return” is pressed
• Return character: '\n', which is not included in the received string
‣ print(comma, separated, values) Converted to string, see str(..), and sent to console
• Output on screen each value separated by space ending with '\n'
Caller can mention
‣ print(comma, separated, values, sep=', ', end='')
named params
Some params can have
default values
Files Python Review
‣ Special type: container of a sequence of characters (or bytes)
• Including ‘invisible’ characters
• Associated with a file managed by the ‘file system’ and known by a name
• Link with File system established using built-in function open(name_of_file)
- Requires advance notice of intent (reading, writing, or both) r, w, a, r+
‣ Ordinal, Mutable/Indexable (Only by using built-in functions)
‣ Exposes Internal functions close, read, write, readline, readlines, writelines ..
• Must filevar.close() for writes to take effect
‣ Shortcut: with open(name_of_file) as filevar:
Coding Practice Python Review
‣ Start with the full specification of the problem
• The output for every input should be clear
• TDD: Write test cases before writing code and algorithm (can refine later)
‣ Write steps in English (or any natural language) first
• A friend should be able to understand and complete the instructions
‣ Make programs “readable”: Appears similar to English
• Use names that reflect their purpose, Add English comments
‣ Defensive programming: Rigorously check for errors
Grading will consider some of these