PythonNotes v2
PythonNotes v2
2
The latest major release of Python, Python 3.0, was released in December 2008
after a long period of testing. One of the main emphases in the design of Python
3.0 was to remove duplicate constructs and modules to provide one and preferably
only one obvious way for doing a task. Consequently, this version is not backward
compatible with previous versions.
The current version of the language and the related documentation are available at
the official website of Python at http:// [Link]
This documentation explains the major features of the language to enable you to
develop procedure-oriented programs using Python.
Python code is interpreted. If you are more familiar with the edit, build, execute cycle, this
might
seem simplistic.
But Python's object-oriented philosophy goes beyond that of these other languages, as
evidenced by
two simple differences. First, all data values in Python are encapsulated in relevant object
classes. Second, everything in a
Python program is an object accessible from within your program, even the code you write.
Python, on the other hand, does not have simple types like int -- only object types. If you
need an integer value in Python, you
merely assign an integer value to the appropriate variable, such as i = 100. Under the
covers, Python creates an integer object
and assigns the variable to reference the new object. Now comes the real kicker: Python is a
dynamically typed language, so you
don't have to declare a variable's type. In fact, a variable's type can actually change
(multiple times) during a single program.
You can classify all the Python classes below the PyObject class into four main categories
that the Python run-time interpreter
uses:
Simple types -- The basic building blocks, like int and float
Container types -- Hold other objects
Code types -- Encapsulate the elements of your Python program
Internal types -- Used during program execution
3
Python has five simple built-in types:
● bool,
● numeric types
o int : These represent numbers in an unlimited range, subject to available
(virtual) memory only.
o Float : represent machine-level double precision floating point numbers
o Complex : represent complex numbers as a pair of machine-level double
precision floating point numbers. The real and imaginary parts of a complex
number z can be retrieved through the read-only attributes [Link] and
[Link].
Boolean expressions
b = 10 > 12
Python provides support forbinary, octal (base 8) and hexadecimal (base 16)
numbers. To tell Python that a number should be treated as an binary,octal or
hexadecimal numeric literal, simply append 0b(or 0B),0o(or 0O) or 0x(or 0X) to
the front of the decimal number.
● Syntax
● Semantics
Syntax: Syntax refers to the grammar of the language which defines the ways
symbols can be combined to create grammatically correct (well-formed or
syntactically correct) sentences (or programs) in the language. Syntax deals only
with the correctness of structure of symbols (form) in a language but not with the
meaning of the correct structures.
4
Semantics: Semantics assign unique meaning for syntactically valid symbol
structures in a language. Thus, semantics define the behavior that a computer
follows when executing a program in the language.
● The elements of the set of terminals are the elements of the language being
described.
● A rewriting rule takes the form A ::= B, where A is a non-terminal and B is a
string of terminals and non-terminals. This expression can be read as ‘ A is
defined as B’ or ‘A can be replaced by B’.
● In the rewriting rules the meta-symbols ‘|’ and ‘ɛ’ are used to denote
alternatives and the empty string respectively.
● All valid statements of the language can be generated by starting from the
start symbol and by applying rewriting rules repeatedly till a string of only
terminals resulted.
● White space is used to separate different items.
Example 4.1
Meta-character Meaning
5
* zero or more repetitions of the preceding item
() Grouping of items
"" Delimiters for literal strings
Example 4.2
5. Program structure
Generally, a program can be considered as a sequence of instructions for the
computer to carry out a specific task(s). The sequence of instructions is coded as a
sequence of physical lines in a program. A single physical line of a program may
contain more than a single instruction. Also, a single instruction may span across
multiple contiguous physical lines. The instructions in a program should adhere to
the rules (grammar) of the programming language.
6
When a physical line ends in a backslash (‘\’ followed by enter) , it is joined
with the following physical line forming a single logical line, deleting the
backslash and the following end-of-line character.
Example :
x=1+\
2
These two physical lines are combined together to form the single logical
line
x=1+2
Note : Where you start the second line is not important as the interpreter
joins the two lines into a single one.
Blank lines
A logical line that contains only spaces, tabs, form feeds and possibly a
comment, is ignored. However, in the standard interactive interpreter, an
entirely blank logical line terminates a multi-line statement.
Example :
x = {8:'a',9:
'b',10:'c'}
In the above statement, the second physical line is ignored by the interpreter.
7
Exercise : Quiz 1
6. Grouping Statements
A region of program text treated as a single unit is called a block. Blocks enable a
group of statements to be abstracted as a single statement. The programming
languages that allow blocks are called Block-Structured Languages.
a) Indentation
Whitespace (spaces and tabs) at the beginning of the logical line is called
indentation. In Python indentation is used to determine the grouping of
statements. This means that statements which go together must have the
same indentation and such a sequence of statements with the same
indentation is treated as a block. Therefore, Whitespace at the beginning of
the line is important in Python and also one cannot arbitrarily start new
blocks of statements.
At the time of execution, tabs found in programs are replaced (from left to
right) by one to eight spaces such that the total number of characters up to
and including the replacement is a multiple of eight. The total number of
spaces preceding the first non-blank character then determines the line’s
indentation. Indentation is rejected as inconsistent if a source file mixes tabs
and spaces improperly.
Example :
a,b = 2,1
if (a > b):
print(a) # tab is used
print(b) # spaces are used
8
Except at the beginning of a logical line, the whitespace characters can be
used freely to separate elements of a line.
Note :
Do not use a mixture of tabs and spaces for the indentation as it does
not work across different platforms properly.
7. Compound Statements
A Compound statement consists of one or more ‘clauses’. A clause is made up of
a header followed by a group of statements controlled by the clause (‘suite’). Each
clause header begins with a uniquely identifying keyword and ends with a colon.
The clause headers of a particular compound statement are all at the same
indentation level.
Example :
if x > 100 :
ptint('Excellent')
y=3
elif x > 50 :
print('Good')
y=2
elif x > 30 :
print('Must improve')
y=1
else :
print('Fail')
y=0
8. Comments
9
Comments are used to embed descriptions in programs. Comments are ignored by
the Interpreter.
In Python a comment starts with a hash character (#) (that is not part of a string
literal), and ends at the end of the physical line. A comment marks the end of the
logical line unless it is embedded in a physical line that is joined to another
physical line through the implicit line joining rules. If a comment is embedded in a
logical line that spans multiple physical lines, the comment is removed when
joining the physical lines together at the time of execution.
Example:
a = [1, # this does not mark the end of the line
2,3]
a = 2 + 3 # A comment
a = 'abc # this is not a comment'
9. Reserved Words
Python has assigned special meanings to a set of words. These words are known as
reserved words or keywords within the language. These reserved words cannot
be used as constants or variables or as any other identifier names. When these
reserved words are used for the intended purpose they must be spelt exactly as
given in the language definition.
10. Delimiters
10
A delimiter separate one token from another . Python uses the following symbols as
delimiters.
( ) [ ] { }
, : . ; @ =
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
Exercise : Quiz 3
Operations on objects
Operation Description
is compares the identity of two objects and returns ‘True’ if two objects are
identical else return ‘False’
Examples
a=2
b=2
a is b True
a=2
b=3
11
a is b False
a = 2.7
a = 2.7
12. Identifiers(Names)
An identifier is a name that identifies an object (variable ,function, class etc).
Different languages use different rules for naming objects. In Python the following
rules must be observed in naming objects.
● A name should start with a letter (No special character such as , \,? Is
allowed)
● The characters after the first one can be a letter, except the special
characters, or a digit from 0 to 9 or the character ‘_’.
● There is no upper limit to the number of characters in a name.
● Reserved words cannot be used as identifiers.
● Identifiers are case sensitive. This means upper case letters are different
from lower case letters. For example, the identifiers Name and name are two
different identifiers.
Example 4.2
Valid Python Identifiers
_name A8 my_name
ගම්
98 2Name my name
-name name#
● Sequences
o Immutable sequences
▪ Strings
▪ Tuples
▪ Bytes
o Mutable sequences
▪ Lists
▪ Byte Arrays
● Set types
o Sets
o Frozen sets
● Mappings
o Dictionaries
Values of some type of objects can be changed. These objects are called mutable
objects whereas objects whose values cannot be changed once they are created are
called immutable objects. An object’s type defines its mutability. For example,
numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
13
Some types of Python objects are capable of returning their members one at a time.
Such objects are called iterable objects. Examples of iterables include all objects
of type sequence (such as list, str, and tuple) and some non-sequence typed objects
like dictionaries.
When the length of a sequence is n, the index set contains the numbers 0, 1, ..., n-1.
Item i of sequence a can be accessed by using the construct a[i]. Sequences are
are either immutable or mutable.
Set types : Represent unordered, finite sets of unique, immutable objects. They
cannot be indexed by any subscript. However, they can be iterated over.
Mappings : Represent finite sets of objects indexed by arbitrary index sets. The
subscript notation a[k] selects the item indexed by k from the mapping a.
Behave like the values 0 and 1 for the values ‘True’ and ‘False’ respectively.
Examples : True + 2 = 3
14
● A tuple of one item (a ‘singleton’) is formed by affixing a comma to
an expression
● An empty tuple is formed by an empty pair of parentheses.
Exercise : Quiz 4
● Floating point
● Integer
● String
c) Floating point literals
Floating point literals are described by the following lexical definitions:
Examples
15
3.14 10. .001 1e100 3.14e-10 0e0
d) Integer literals
Integer literals are described by the following lexical definitions:
Examples :
0, 123, 0b11, 0x11
e) String literals
String literals are described by the following lexical definitions:
One syntactic restriction not indicated by these rule is that whitespace is not
allowed between the string prefix and the rest of the literal.
16
Examples :
The letter 'r' or 'R' are used to denote raw strings. In raw strings, backslashes
are treated as literal characters. For example, in a raw string '\n' is not
treated specially. Unless an 'r' or 'R' prefix is present, escape sequences in
strings are interpreted according to rules.
Escape Sequences
An escape sequence comprises of the escape character “\” followed by some
other character. An escape sequence has a special meaning inside a string
literal.
15. Variables
A variable is the symbolic name assign for a place in the computer's memory
where one can store data. Variables are used in a program to retain data
temporarily in the main memory of the computer. Once a variable is created it’s
name can be used either to store data in a specific location or to retrieve data stored
in that specific location in the computer memory. Once a variable is created by a
program that variable can be used to store different values of the same data type,
17
at different times, during the program execution. For example consider the Python
statement i = 0. When executing this statement, the following actions take place.
1. A storage segment is acquired from the main memory to store a data value
of type integer, and assigned the symbolic name i for the storage segment.
2. Store the value 10 at this storage secion.
Once this is done, the value stored at that location(10) can be retrieved by using the
symbolic name i.
Consider the following python program segment
i=5
j=8
k=i+j
16. Operators
Operators prescribe action on data. The actions indicated by the operators
are performed on the specified data at the time of program execution. The
18
various operations defined by Python can be grouped into several classes as
described below.
a) Mathematical Operators
Arithmetic conversions
10.2 + 5 = 15.2
- Subtraction 1 – 2 = -1
10.5 – 3 = 7.5
2*3=6
4.0/2 = 2.0
19
numbers as well
% Remainder 7%4=3
7.0 % 4 = 3.0
** Exponentiation 2 ** 3 = 8
2.0 ** 3 = 8.0
b) Logical Operators
Logical operators must have operands of type Boolean and the results are
also of type Boolean.
Any object can be tested for truth value. The following values are considered
false:
All other values are considered true. Therefore, objects of many types are
always true.
20
not not not True = False
Exercise : Quiz 5
c) Comparison Operators
Comparisons yield Boolean results.
Operator Meaning Example
== Equal
!= Not equal
Note : Objects of different types, except different numeric types are never
compared equal.
Exercise : Quiz 6
21
d) Identity tests
Identity tests yield Boolean values.
The operators is and is not test for object identity.
Examples:
x is y # true if and only if x and y are the same object
x is not y # true if and only if x and y of different objects.
e) Bitwise operators
~ Negation
| Or
& And
^ XOR
f) Membership tests
Membership tests yield Boolean values.
22
x in s evaluates to true if x is a
in
member of s, and false otherwise
Examples :
Tuple :
x = (1,10.2,’abc’)
Print(x[2])
List :
x = [1,10.2,’abc’]
Print(x[2])
Dictionary:
x = {1:10,’abc’:10.5,’c’:’nimal’}
print(x['c'])
Set:
X = set([])
x = set(['sunil','gamini','nimal',5,2])
y = set([‘sunil’,’kamal’])
z = [Link](y) z=x|y
z = [Link](y) z=x&y
[Link]('saman')
‘saman’ in x
[Link]('saman')
[Link]()
Operators Description
or Boolean OR
23
and Boolean AND
<,<=,>,>=,!=,== Comparisons
| Bitwise OR
^ Bitwise XOR
~x Bitwise NOT
** Exponentiation
X[index] Subscription
X[index1:index2] Slicing
Operators with the same precedence are listed in the same row in the table above. For
example, + and - have the same precedence.
24
a) Changing the order of evaluation
The default order of evaluation can be changed by using parentheses. If
parentheses are used in an expression to group items, the expressions in the
parentheses are evaluated first, starting from the innermost parenthesis to
outermost parenthesis.
b) Associativity
Operators with the same precedence are computed from left to right.
Example :
3 - 2 + 3 = (3 – 2) + 3 = 4
Syntax :
Semantic:
If the target list is a comma-separated list of targets, the object yields after evaluating
the expression_list must be an iterable with the same number of items as there are
targets in the target list, and the items are assigned, from left to right, to the
corresponding targets.
The trailing comma is required only to create a single tuple (a.k.a. a singleton). It is
optional in all other cases.
25
Examples
Example Semantic :
a=2
mylist = [1,2,3]
mylist[2] = ‘a’ modify both the value and the type of the third
item of the list mylist
a = 2,3 a = (2,3)
26
program from top to bottom. This default flow of control can be changed by using if,
while and for control structures.
In Python all these control flow constructs are implemented as compound statements.
a) The if statement
The if statement is used for conditional execution.
Syntax:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
Semantic:
It selects exactly one of the suites by evaluating the expressions one by one until
one is found to be true; then that suite is executed (and no other part of the if
statement is executed or evaluated). If all expressions are false, the suite of the
else clause, if present, is executed.
c) The while statement
The while statement is used for repeated execution as long as an expression is
true:
Syntax:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
Semantic:
This structure repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the suite
of the else clause, if present, is executed and the loop terminates.
Break and Continue statements
A break statement executed in the first suite terminates the loop without
executing the else clause’s suite. A continue statement executed in the first suite
skips the rest of the suite and goes back to testing the expression.
20. Functions
What one should know about functions.
● Why functions.
● Structure of functions.
● Local and Global variables
● Function calling
● Parameters and Arguments– Positional and Keyword arguments
● Default argument values
● Recursive functions
A function is a named sequence of statements that performs a desired operation(s). The operation(s) desired is
specified in a function definition.
Functions allow program segments to be extracted as independent units and to be reused them any number of
times within the same program or in different programs. Functions eliminate the need for a repetitive code.
Python provides a large collection of built-in functions. Also the language allows one to build one’s own functions.
28
def function_name(parameter_list):
suite
The keyword def starts (introduces) a function definition. The keyword def must be followed by the name of
the function followed by a parenthesized list of formal parameters terminated by the symbol “:” . This line is
called the header of the function. What followed after the “:” in the function definition forms the body of the
function. The statements in the body must be indented.
The function_name is an identifier. Therefore, when constructing function names one should follow the rules for
identifiers. The formal parameters provides a mechanism to send values to the function and these parameters are
used to control the work of the function. The parameter list may be empty, or may contain any number of
parameters.
A function gets executed only when the function is called. A function may perform computations and always
return a value when it is called.
A function may call other functions. Also, functions must be created before executing them. In other words, the
function definition should be executed before the function is called.
examples :
if a > b: print()
return a
else:
return b
b) Function call
A function is executed by a function call. A function call contains the name of the function being executed
followed by a list of values, called arguments. The value of arguments are assigned to the parameters in the
function definition at the time of function execution.
29
There are two ways of assigning arguments to formal parameters; namely by position or by key words. When
arguments are assigned to formal parameters by position, there should be a one to one mapping, by position,
between the arguments in the function call and the formal parameters in the function definition. When values are
passed by using keywords the arguments in the function call should take the form keyword = value, where the
keywords are the names of a formal parameter.
When positional and key word arguments are mixed in a function call then the argument list must have any
positional arguments followed by any keyword arguments.
All parameters (arguments) in the Python language are passed by reference. It means if you change the value of a
parameter within a function, the change also reflects back in the calling function.
Exercise : Quiz 8
f) Recursive functions
A function may call itself during its execution. Such a function is called a recursive function. Recursive
functions should have a terminal condition to stop the execution, otherwise, the recursion will repeat
forever, causing the program to crash or to hang the entire computer system.
Example :
def fact(a):
if a == 1:
return 1
else:
return (a * fact(a-1))
Python decides the scope of a variable based on where you initialize the variable. If you initialize a
variable inside a function, that variable is treated as a local variable, otherwise the variable is treated as
a global variable. The global variables can be referenced inside a function, but cannot assign values
within a function (unless named in a global statement).
30
Exercise : Quiz 9
h) DocStrings
Python documentation strings (DocStrings) enable descriptions of programs to be embedded with the
programs. Doc strings start and terminated with the characters “””. When using docstrings, the python
convention is to embed the documentation as a multi-line string where the first line starts with a capital
letter and ends with a dot. Then the second line is left as a blank line followed by any detailed
explanation starting from the third line. The DocString of a function can be displayed by using either the
help() function or the __doc__ variable.
Example :
>>> import sys
>>> help(sys)
>>> help([Link])
21. Modules
Python allows one to reuse code across different programs by organizing them in separate files. Every
Python program is considered as a module. A module file should have a .py extension. To use the
functions of a module in a program that module must be imported to that program using the keyword
import.
Example 1:
import module_name
Example 2:
from module_name import function_name1,……..
When executed, the import statement looks for the named module in the following locations in that
order ;
● in the current directory (the director where you program is in),
● in one of the directories listed in its [Link] variable.
This means that one can directly import modules located in the current directory. Otherwise, one will
have to place one’s module in one of the directories listed in [Link] .
31
Exercise : Quiz 10
Exercises
Quiz 1 : Identify the different tokens in [Link] program.
Quiz 2 : Find the syntax and semantics of the following reserved words from the Python manual.
Quiz 4: A tuple of one item should be formed by affixing a comma to the item. For example (1,) defines a
tuple consisting only the item 1. Explain why a comma should be affixed in this definition.
Quiz 5 : The operators ‘or’ and ‘and’ are described as short–circuit operators. What is a short-circuit
operator? Show by using an example how a short-circuit operator operates on its operands.
Quiz 6 : [1,4,2] < [1,5] returns the Boolean value ‘True’. Explain why. Experiment how logical operators
work on tuples and lists.
Quiz 7 : Consider the following Python programs. What are the output of them
32
#program [Link] #program [Link]
for i in range(0,10,2): ගම් = ('මහරගම','නුවර','ගාල්ල')
Print(i) for ගම in range(len(ගම්)):
print(ගම්[ගම])
Quiz 8 : Consider the Python program [Link] given below. Identify the local variable, global
variables defined in the functions readData and writeData. Also, identify the parameters used in the
function definitions and the arguments used in each function call. What any the default values in the
function definitions?
def varscope():
i=8
print(i)
print(i)
varscope()
print(i)
What is the output of the above program and why do you get that output ?
Quiz 10 : How do you add a new path to [Link]? What is the naming convention you have to use to call
a function in an imported module.
def readData():
global recordcount
i=0
33
print('Getting data for record :'+ str(recordcount))
for value in dataitems:
datavalues[i] = input(value + ": ")
i=i+1
recordcount += 1
print()
def writeData(name,age,telephone,sex='M'):
[Link](name+','+
age+','+
telephone+','
+sex+
'\n')
[Link]()
Python Quiz
2) If a = (1,4,5) and b = [11,23,45] which of the following Python expression are valid ?
a) print(a[0]) b) a[1] = 10 c) b[1] = 34
34
d) b[3] = 34 e) b[1] = a
a = { ‘a’: 1, a=5+\ a = 4; b = 2
{‘b’:2} 2
6) Which of the following Python expressions evaluated to the Boolean value ‘True’
35
b) [1,5] > [1,2,3] b) True and False c) 1 in (1,2)
e) not [] e) 5 >= 5
a) -4 b) 10 c) 11
d) 8 e) 3
# program : [Link]
i=5
def varscope():
i = 50
print(i + 1,end=’,’)
i=i+1
print(i,end=’,’)
varscope()
36
print(i)
def example1(a):
if a == 1:
return 1
else:
return a* example1(a-1)
print(example1(3))
a) 1 b) 2 c) 3
d) 6 e) 8
37