0% found this document useful (0 votes)
2 views37 pages

PythonNotes v2

This document is a tutorial on programming in Python, covering topics such as computer operations, Python's features, syntax, semantics, program structure, and data types. It explains the differences between low-level and high-level programming, the importance of indentation in Python, and provides an overview of Python's reserved words and delimiters. The tutorial serves as a comprehensive guide for understanding and utilizing Python effectively.

Uploaded by

ICT Class
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

PythonNotes v2

This document is a tutorial on programming in Python, covering topics such as computer operations, Python's features, syntax, semantics, program structure, and data types. It explains the differences between low-level and high-level programming, the importance of indentation in Python, and provides an overview of Python's reserved words and delimiters. The tutorial serves as a comprehensive guide for understanding and utilizing Python effectively.

Uploaded by

ICT Class
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming in Python

This tutorial is aimed at reviewing the following areas in programming specially in


the use of the programming language ‘Python’ in programming.

1. Low-Level and High-Level Computer Operations


2. What is Python?
3. Syntax and Semantics of programming languages
4. Extended BNF notation
5. Program structure
6. Grouping statements
7. Compound statements
8. Comments
9. Reserved words
10. Delimiters
11. Data and Objects
12. Identifiers(Names)
13. Data types
14. Literals (Constants)
15. Variables
16. Operators
17. Operator Precedence and Associativity
18. Assignment statements
19. Control Flow structures
20. Functions
21. Modules

1. Low-Level and High-Level Computer Operations


Every computer is based on a set of instructions built into the hardware. These
instructions, in general, are simple and specific to the hardware of the particular
type of the computer and also, these instructions are designed for the hardware
but not for humans to follow. Thus, developing programs using these instructions
is difficult, time consuming and error-prone. However, in the early days,
programming was done based on such instructions. Later, higher-level languages
were developed to ease programming. These high-level languages enable
1
programmers to write instructions in a format that was easy for humans to manage
and understand.

No computer can understand any of the high-level language instructions directly.


Therefore, a special program(s) must be used to translate instructions in high-level
language into a machine language. Such programs are known as language
translators.

Computer programs can be translated into an executable code(machine code) by


using
● Compilers
● Interpreters or
● A combination of compilers and interpreters

A compiler is a computer program(s) that transforms a program (source code)


written in a programming language(source language) into another computer
language (target language) without changing the logic of the source code. Often,
the target language is in binary form (object code) that can be directly executed by
a computer. A compiler makes the translation only once. Once the object code is
generated it can be executed any number of times without the support of the
compiler. In contrast, an interpreter converts a program every time it is executed.
Therefore, the programs based on interpreters cannot be executed in the absence of
their associated interpreters.

"low level language" since the code directly manipulates the


hardware of the computer.
Variables are place holders for data a program might use or
manipulate.
2. What is Python?
Python is a high-level, general purpose, interpreted, object-oriented programming
language developed in late 1980 and early 1990. Guido van Rossum at National
Research Institute for Mathematics and Computer Science (CWI) in the
Netherlands is the principal author of Python. Python supports procedure-
oriented as well as object-oriented programming.

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.

The flexible nature of the Python programming language supports multiple


programming philosophies, including procedural, object-oriented, and functional. But most
importantly, programming in Python is fun. The language supports rather than hinders the
development process.
Python is an agile, dynamically typed, expressive open source programming language that
can be freely installed on a variety of
Platforms

Python code is interpreted. If you are more familiar with the edit, build, execute cycle, this
might
seem simplistic.

everything in Python is an object.

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].

These types are immutable, which means that


when an integer object is created, its value cannot be changed.

The Boolean type


The simplest built-in type in Python is the bool type, which can hold only one of two
possible objects: True or False:

Boolean expressions
b = 10 > 12

Concepts of slicing and packing or unpacking,??????????????????????

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.

3. Syntax and Semantics of programming languages


Any language definition consist of two main components

● 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.

4. Extended BNF notation


Backus-Naur form (BNF) is one of the meta-languages used to describe the syntax
of many high-level languages consciously. A BNF grammar comprises a set of
terminals, a set of non-terminals, a set of rewriting rules and a start symbol which
is a non-terminal. A BNF grammar has the following characteristics.

● 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.

A BNF grammar of a language can be used to generate all possible valid


statements of that language.

Example 4.1

name ::= lc_prefix_char lc_suffix


lc_suffix::= lc_suffix_char lc_suffix | ɛ
lc_prefix_char ::= "a"|..|"z"
lc_suffix_char ::= "a"|..|"z"|”_”

The syntax of Python is described by using an extended version of the BNF


notation (EBNF). In this notation the following additional meta-characters are used
in the rewriting rules.

Meta-character Meaning

5
* zero or more repetitions of the preceding item

+ one or more repetitions of the preceding item

[] zero or one occurrences of items inside [ ] - This means what is


inside is optional.

() Grouping of items
"" Delimiters for literal strings

Table 4.1 : Meta Character used in EBNF

Example 4.2

name ::= lc_letter (lc_letter | "_")*


lc_letter ::= "a"..."z"

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.

A Python program comprises a sequence of statements. Each statement in a


program is either a simple statement or a compound statement. A statement
(logical line) may be coded in multiple contiguous physical lines by following the
explicit or implicit line joining rules. A physical line comprises a sequence of
characters terminated by an end-of-line sequence (for example in Windows form
the ASCII sequence CR LF character sequence). Sequence of characters in a
logical line can be combined into a pre-defined set of units called tokens, namely,
white spaces, identifiers, keywords, literals, operators, and delimiters.

a) Explicit line joining

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.

b) Implicit line joining


Expressions in parentheses( ‘()‘,’[]‘,’{}’) can be split over more than one
physical line without using backslashes.
Example :
x = {8:'a',9:
'b',10:'c'}

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.

Different languages have implemented the notion of blocks differently. For


example ALGOL family of languages use the key words ‘begin’ and ‘end’ as block
delimiters whereas the C family of languages use curly braces as block delimiters.
Python uses yet another syntactic structure, indentation, to demark blocks.

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

SyntaxError : inconsistent use of tabs and spaces in indentation

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.

A suite can be coded as

● one or more semicolon-separated simple statements on the same line as the


header, following the header’s colon, or
● one or more indented statements on subsequent lines.

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.

Python reserved words are listed below.

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Exercise : Quiz 2

10. Delimiters

10
A delimiter separate one token from another . Python uses the following symbols as
delimiters.
( ) [ ] { }
, : . ; @ =
+= -= *= /= //= %=
&= |= ^= >>= <<= **=

Exercise : Quiz 3

11. Data and Objects


Data in a Python program is represented as objects. Every object has an identity, a
type and a value. An object’s identity and the type never changes once it is created.

Operations on objects

Operation Description

id() returns an integer representing the identity of the object

type() returns the object’s type

is compares the identity of two objects and returns ‘True’ if two objects are
identical else return ‘False’

Examples

Example Result (in bold)

a=2

b=2

a is b True

a=2

b=3

11
a is b False

a = 2.7

type(a) <class 'float'>

a = 2.7

id(a) Some integer like 31356704

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
ගම්

Invalid Python Identifiers

98 2Name my name
-name name#

13. Data Types


12
A data type is a name or label given to a set of values with predefined
characteristics and operations that can be performed on that set of values. The type
of a data item has to be known before used in a program. Programming languages
can be classified either as statically types or dynamically types based on when
(compile-time or run-time) the type checking is done.

Python is a dynamically typed language. Therefore variables need not be defined


before they are used. In Python values carry types and the type of a variable is
inferred from the value assigned to that variable. Thus, a variable may have
different types at different places in a program.

Python standard data types


Some of the built in data types provided by Python are:
● Numbers
o Integral
▪ Integer
▪ Boolean
o Real
o Complex

● 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.

Numbers : Represent mathematical numbers, but are subject to the limitations of


numerical representation in computers.

Sequences : Represent finite ordered sets indexed by non-negative numbers. The


built-in function len() returns the number of items of a sequence.

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.

Data Type Description

Integers These represent numbers in an unlimited range, subject to available (virtual)


memory.

Examples : 23, -20

Boolean Possible values are ‘True’ or ‘False’

Behave like the values 0 and 1 for the values ‘True’ and ‘False’ respectively.

When converted to a string, the strings "False" or "True" are returned,


respectively.

Examples : True + 2 = 3

Strings The items of a string object are Unicode code units

Tuples Sequence of Python objects.

● Tuples of two or more items are formed by comma-separated lists of


expressions.

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.

Bytes Array of 8-bit bytes.

Each byte is represented by integers in the range 0 <= x < 256.

Lists Sequence of an arbitrary collection of objects

Sets Mutable sets

Frozen sets Immutable sets

Dictionaries Represents finite sets of objects indexed by arbitrary values.

Exercise : Quiz 4

14. Literals (Constants)


A literal is a notation for representing a fixed value of a built-in type
in source code.

A few main types of literals provided by Python

● Floating point
● Integer
● String
c) Floating point literals
Floating point literals are described by the following lexical definitions:

floatnumber ::= pointfloat | exponentfloat


pointfloat ::= [intpart] fraction | intpart "."
exponentfloat ::= (intpart | pointfloat) exponent
intpart ::= digit+
fraction ::= "." digit+
exponent ::= ("e" | "E") ["+" | "-"] digit+

Examples

15
3.14 10. .001 1e100 3.14e-10 0e0

d) Integer literals
Integer literals are described by the following lexical definitions:

integer ::= decimalinteger | octinteger | hexinteger | bininteger


decimalinteger ::= nonzerodigit digit* | "0"+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
octinteger ::= "0" ("o" | "O") octdigit+
hexinteger ::= "0" ("x" | "X") hexdigit+
bininteger ::= "0" ("b" | "B") bindigit+
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
bindigit ::= "0" | "1"

Examples :
0, 123, 0b11, 0x11

e) String literals
String literals are described by the following lexical definitions:

stringliteral ::= [stringprefix](shortstring | longstring)


stringprefix ::= "r" | "R"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source character except "\" or newline or the
quote>
longstringchar ::= <any source character except "\">
stringescapeseq ::= "\" <any source character>

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 :

r ‘1234’ # this is not a valid string literal

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.

\ Backslash and newline


newline ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)

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

The following actions are performed when executing this program


1. Acquire enough memory to store an integer value, assign the symbolic name
i for this memory and store the value 5 at that storage segment.
2. Acquire enough memory to store an integer value, assign the symbolic name
j for this memory and store the value 8 at that storage segment.
3. Retrieve the values at the storage locations, identified by the symbolic name
i and j, add those two values together, acquire another storage to store an
integer value and store the result at that storage segment.
One should be aware of the following facts when using variables.
● A variable is a symbolic name assign to a memory segment to store values.
● A variable can be used to store different values at different times of the
program execution. When a new value is stored the previous value is erased
by the new value.
● Binding of names to storage is a temporary action. When the program
terminates all memory acquired by the program for variables is released
back to the computer.
● When the computer switched off or out of power, all variables will be
automatically erased out from the memory.

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

If a binary mathematical operator is applied to two numbers of different


types, the following rules are used in the computation, in that order.
● If either argument is a complex number, the other is converted to
complex;
● If either argument is a floating point number, the other is converted to a
floating point;
● When both values are integers no conversion is done.
Operator Meaning Example
+ Addition 1+2=3

10.2 + 5 = 15.2

‘ab’ + ‘cd’ = ‘abcd’

- Subtraction 1 – 2 = -1

10.5 – 3 = 7.5

* Multiplication 2.0 * 3 = 6.0

2*3=6

/ Division 4/2 = 2.0

4.0/2 = 2.0

/ division always results in a floating-point


number.

// Integer Division 5//2 = 2

The result of the division is truncated to an


integer. Works for integers and floating-point

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.

Truth value testing

Any object can be tested for truth value. The following values are considered
false:

● None (This is a special Python value)


● False
● zero of any numeric type, for example, 0, 0.0, 0j.
● any empty sequence, for example, '', (), [].
● any empty mapping, for example, {}.

All other values are considered true. Therefore, objects of many types are
always true.

Operator Meaning Example

or or True or False = True

(1 > 2) or (4 > 2) = True

and and True and False = False

(1 > 2) and (4 > 2) = False

20
not not not True = False

Note : The operators ‘or’ and ‘and’ are short–circuit operators.

Exercise : Quiz 5

c) Comparison Operators
Comparisons yield Boolean results.
Operator Meaning Example

< Strictly less than 1< 2 # True

‘a’ > ‘z’ # False

> Strictly greater


than

<= Less than or equal

>= Greater than or


equal

== 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

Operator Meaning Example

~ Negation

| Or

& And

^ XOR

<< Shift left

>> Shift right

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x <


y and y <= z, except that y is evaluated only once (but in both cases z is not
evaluated at all when x < y is found to be false.
Operation on data Types

f) Membership tests
Membership tests yield Boolean values.

Operator Meaning Example

22
x in s evaluates to true if x is a
in
member of s, and false otherwise

not in x not in s evaluates to false if x


is a member of s, and true otherwise

a) Managing objects of different types

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]()

17. Precedence Rules


Python operator precedence from lower precedence to higher precedence is given in
the following table.

Operators Description

or Boolean OR

23
and Boolean AND

not x Boolean NOT

in, not in Membership tests

is, is not Identity tests

<,<=,>,>=,!=,== Comparisons

| Bitwise OR

^ Bitwise XOR

& Bitwise AND

<<,>> Bit shift

+,- Addition, subtraction

*,/,//,% Multiplication, Division, Floor Division and


Remainder

+x,-x Unary addition and subtraction

~x Bitwise NOT

** Exponentiation

[Link] Attribute reference

X[index] Subscription

X[index1:index2] Slicing

f(argument) Function call

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

18. Assignment statements


Assignment statements are used to (re)bind names to values or to modify attributes or
items of mutable objects.

Syntax :

assignment_stmt ::= (target_list "=") + (expression_list)

target_list ::= target ("," target)* [","]

Semantic:

If the expression_list is a comma-separated list of expression, evaluating the expression


list yields a tuple. An assignment statement evaluates the expression list and assigns
the single resulting objects to each of the items in target lists, from left to right.

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 Bind the symbolic name (variable) a to the integer


value 2.

a=2

a = ‘Gamini’ Re-bind the string ‘Gamini’ to the symbolic name


(variable) a
mylist = [1,2,3]
modify the third item of the list mylist
mylist[2] = 6

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)

a,b = 2*3, 2+3 a = 6, b = 5

a,b = b, a Swapping two values

a,b = 1,2,3 Error as the number of items in the target_list is


not the same as the number of items in the
expression list

19. Control Flow structures


Execution of a Python program always begins at the first statement of the program. The
statements in a program are executed one at a time, in order of their appearance in the

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.

d) The for statement


The for statement is used to iterate over the elements of a sequence (such as a
string, tuple or list) or other iterable object:
27
Syntax:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
Semantic :
The expression list is evaluated once; it should yield an iterable object. The suite
is then executed once for each item in the iterable object , in the order of
ascending indices. Each item in turn is assigned to the target list, and then the
suite is executed. When the items are exhausted, the suite in the else clause, if
present, is executed, and the loop terminates.
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 continues with the next item, or with the else
clause if there was no next item.
The suite may be assigned to the variable(s) in the target list; this does not affect
the next item assigned to it.
Exercise : Quiz 7

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.

a) Structure of a python function


The structure of a Python function is given below.

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 :

def max(a,b): def ln():

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.

c) Default Argument Values


In the function definition formal parameters can be assigned with default values. This enables functions to be
called with fewer arguments than in the definition. When such a function is called without providing a value for a
formal parameter with a default value, the default value for that parameter is assumed. The default value is
evaluated only once and shared between subsequent calls.

d) Binding arguments with formal parameters

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.

e) Function Return Values


A function always returns a value when it is called. When the return value of a function is not explicitly specified
the built in value None is returned. The return statement can be used to return a specific value (object) to the
caller. A return statement without an expression returns the value None. Falling off the end of a function without
a user defined return statement also returns the value None.

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))

g) Local and Global Variables (Scope of variables)


Variables found in a function can be classified either as global variables or as local variables. Global
variables are accessible from inside and outside the function whereas local variables are only accessible
from inside the function.

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

Looks for a file named module_name.py and reads it in (initialize)

Example 2:
from module_name import function_name1,……..

Imports specific functions named function_name1,…… from a module named


module_name.py

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.

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Quiz 3 : Identify the delimiters used in [Link] program.

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?

Quiz 9 : Consider the following Python Program.


Example :
# program : [Link]
i=5

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.

# Program name : [Link]


f = open('[Link]', 'w')
dataitems = ("name","age","sex","telephone")
datavalues = ["","","",""]
recordcount = 1

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')

datavalues[0] = 'dummay name'


while datavalues[0]:
readData()
if(datavalues[0]):
writeData(datavalues[0],datavalues[1],datavalues[3],datavalues[2])

[Link]()

Python Quiz

1) Which of the following identifiers are valid in Python?


a) ගම b) 8Names c)my name
e) My_name e) name#

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

3) Which of the following Python statements are valid ?


a) a,b = 2*3,(3,4) b) a,b = 2 c) x = (a,b) = 3,2
d) a,b,c = 1,4 e) a,b = 2, 'name'

4) Consider the following Python statements

Statement i Statement ii Statement iii

a = { ‘a’: 1, a=5+\ a = 4; b = 2
{‘b’:2} 2

Which of the above statement(s) are valid?

a) iii only b) ii and iii only c) I and iii only


d) I and ii only e) i, ii and iii

5) Which of the following Python data types are immutable?

a) Tuples b) Lists c) Strings


d) Integers e) Dictionaries

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

7) What is the final value of the Python expression 5 – 11%3 ** 2 + 7

a) -4 b) 10 c) 11
d) 8 e) 3

8) Which of the following statement(s) is(are) correct about Python compound


statements?
a. Compound statement can have only one clause.
b. A clause of a compound statement should begin with a unique identifying
keyword.
c. A clause of a compound statement should end with the symbol ‘@’
d. A clause of a compound statement is made up of a header and a collection of
statements controlled by the clause.
e. Clause headers of a compound statement may have different indentation levels.

9) Consider the following Python program.

# program : [Link]
i=5
def varscope():
i = 50
print(i + 1,end=’,’)
i=i+1

print(i,end=’,’)
varscope()

36
print(i)

What is the output of the above program when executed?

a) 5,51,5 b) 5,51,51 c) 50,51,52


d) 5,end=51,end=5 e) end=5,end=51,5

10) Consider the following Python program

def example1(a):
if a == 1:
return 1
else:
return a* example1(a-1)

print(example1(3))

What is the output of the above program?

a) 1 b) 2 c) 3
d) 6 e) 8

37

You might also like