0% found this document useful (0 votes)
3 views63 pages

GET211 Note (Baisc Python 3 Programming)

The document provides an introduction to computer programming using Python, explaining key concepts such as programming parties (client/user, machine, programmer), machine and high-level languages, and the role of interpreters and compilers. It covers essential programming elements including syntax, identifiers, keywords, functions, data types, and the process of running a program. Additionally, it discusses naming and saving data in variables, emphasizing the importance of proper naming conventions and data handling in programming.

Uploaded by

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

GET211 Note (Baisc Python 3 Programming)

The document provides an introduction to computer programming using Python, explaining key concepts such as programming parties (client/user, machine, programmer), machine and high-level languages, and the role of interpreters and compilers. It covers essential programming elements including syntax, identifiers, keywords, functions, data types, and the process of running a program. Additionally, it discusses naming and saving data in variables, emphasizing the importance of proper naming conventions and data handling in programming.

Uploaded by

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

COMPUTING & SOFTWARE

ENGINEERING (GET 211) NOTE


INTRODUCTION TO COMPUTER PROGRAMMING WITH PYTHON 3
CONCEPT OF PROGRAMMING
Programming can refer to the passing of instructions to machine, on how a problem is to be solved. The
machine here refers to any computing device e.g. personal computer (PC), laptops, phone, calculator,
automated teller machine (ATM) etc.

In the concept of programming, there are 3 parties to describe. These are:


1. Client/User: refers to the individual seeking a solution to a problem he/she has. Think of the many
times, you have had to rely on a calculator to get an answer to an arithmetic question.
2. Machine: refers to the computing device that is to produce the solution to the problem.
3. Programmer: refers to the individual who instructs the machine on how to solve the problem of the
client
Passing of instruction from one party to another is a form of communication, and every communication is
based on a language.

LANGUAGE OF A MACHINE AND A PROGRAMMER


A machine has a TRANSISTOR functioning like a basic switch as its building block. A switch has just 2 states
which are ON and OFF. The ON is donated by 1 and OFF by 0.
The fact that a switch has only two states makes it BINARY. On account of this a machine is said to be
binary in nature and as a result only understands instructions in binary form (1’s and 0’s). Instructions of
this sort are said to be in MACHINE CODE/LANGUAGE (LOW-LEVEL language).

A programmer on the other hand, finds it easier writing instructions in languages with words and phrases
resembling those used in the language of men – most popular been English. Such a language is called a HIGH-
LEVEL language, an example of which is Python (LANGUAGE OF INTEREST FOR US). Others are Java, C++, C, Perl
etc.

BRIDGING THE GAP IN COMMUNICATION


From the previous section, it is clear that instructions written by a programmer cannot be understood by the
machine. A third party is therefore needed to make this communication effective. This third party comes in
the form of an application that contains all words and phrases (LEXICON) in the high-level language as well
as their equivalents in machine code. This application is called any of the two names below:

1. INTERPRETER: this converts a statement in the instruction set to its machine code equivalent, waits
for the machine to execute the converted statement, before converting the next statement in the
program.
2. COMPILER: this converts all statements in the instruction set, to their machine code equivalents
before execution of all these statements by the machine commences.

NOTE: There is a language called ASSEMBLY LANGUAGE with words and phrases in the form of short alphanumeric
codes called MNEMONICS. This language is seen as one between high-level language and low-level language. The
application that converts instructions in assembly language to machine code is called an ASSEMBLER.

BASIC COMPUTING ABILITIES OF A MACHINE


If a machine is to be relied on to get a job done, it is only proper to point out what its abilities are.
This will ensure that instructions passed are well within its abilities. Below are some of these abilities:
1. It can output/display data
2. It can receive data from a client
3. It can store/save received data
4. It can process data which may lead to the production of another data.
The last ability is the one targeted the most by instructions in a program.

PROGRAM & SOURCE FILE


A program is a written set of instructions that solves a problem when followed. A source file is the file
that contains a program.

COURSE INSTRUCTOR: T. MIEBI


A source file has both a name and extension. A source file for a program written in Python has the extension
py. If the program is a graphical user interface (GUI) program, it is pyw. An extension is joined to a file
name using a dot (.) i.e. [Link]. For example, [Link], [Link] etc.

SYNTAX & RUNTIME/LOGIC ERRORS


Going by the dictionary meaning of the word “Syntax”, it refers to the set of rules that guides how
statements and phrases in a language are constructed. Python is a language hence; it has its own syntax.
Syntax error refers to an error generated in a program when there is a violation of one or more rules
governing how statements and phrases in a Python program are written. One of the most important rules is the
one about how statement is terminated in Python. English language has full stop for its sentences. What is
the character for Python statements?
1. Statements in Python are terminated with a semi-colon (;).
2. If a statement is alone in a line, it is not compulsory to add the semi-colon
3. If a line contains more than one statement, then each statement before the last must be terminated
with a semi-colon. For the last, it is optional.
Writing more than one statement per line in a program, is not advisable because it reduces the clarity and
readability of the program.

Runtime error on the other hand refers to errors resulting in wrong program about or abnormal behavior. An
error in program output is the result of a mistake in the steps to the solution of the problem.

It is important to state that in a scenario where there is any kind of error, all fingers should be pointed
at the programmer, because he/she is the source of the statements in the program.

IDENTIFIERS & KEYWORDS


An identifier is a name. An acceptable name has to start with a letter (a – z, A –Z), or underscore (_) and
be followed by 0 or more non-white space characters from letters, digits (0 – 9) or the underscore, and it
must not be a keyword – names/identifiers that have already been used by the developers of the programming
language.
The following points are important to note, when choosing a name:
1. A name should be meaningful
2. For multiple-word names, use underscore to separate each word e.g. average_score; or use what is
called camelCase capitalization (each word after the first starts with a capital letter) e.g.
averegeScore, firstScore etc.
3. Shorter meaningful names are better than long ones.
Unlike what obtains in English language, names are case-sensitive which means that Breadth ≠ breadth.
Examples of keywords forbidden as identifiers in programs include: and, as, assert, break, class, continue,
def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal,
not, or, pass, raise, return, True, try, while, with, yield.
Some things to remember when choosing name include:
1. A name should be meaningful
2. Shorter meaningful names are better than lengthy ones.
3. For multiple word names, use _ to separate each name e.g. average_score or use what is called
camelCase capitalization (each name after the first starts with a capital letter) e.g. averageScore,
firstScore, sumFirstSecond etc.
In a nutshell, a valid name must not be a keyword, and must start with letter or underscore and be followed
by zero or more non-white space, letter, underscore, or digit character.

RUNNING A PROGRAM
Running a program is the term given to making the machine executes instructions in a program. This ideally
requires using an Integrated Development Environment (IDE) which is an application that contains among other
things: a text editor for typing and saving the program, as well as an interpreter or compiler that also
provides the output of program execution.
A Python IDE also provides what is called a CONSOLE or INTERACTIVE SHELL in which short program statements
or expressions/commands can be typed and executed with result (if any) returned immediately, without the
COURSE INSTRUCTOR: T. MIEBI
need to save these instructions in a file. These three tools are available in both the IDE’s for PC’s and
smart phones.

Interfaces from IDLE


IDLE comes with the Python interpreter installer. The images below are from the IDLE interface.
1. Console for testing Python statements/commands
The interface for this is opened by double clicking the IDLE shortcut

Commands are typed here

2. Text editor for typing a Python program in a source file


The editor is opened from the above interface by
i. Pressing Ctrl+N on the keyboard
ii. Clicking the menu in the following order: File => New File

Interface from QPython 3 for Android Smart Phones

COURSE INSTRUCTOR: T. MIEBI


Click to open
console
Click to open
editor

Click to
RUN program

Click to
save
program

Console Editor

FUNCTIONS
A function is a block/set of programming statements, meant to perform a specific task. Related functions are
normally organized into what is called a MODULE.
There are functions provided in the Python language, and it is also possible for a programmer to create
his/her own (user-defined) functions.
COURSE INSTRUCTOR: T. MIEBI
A function goes by a name and normally requires 0 or more data called ARGUMENTS to perform its task.
The formats below show how a function is called/invoked/used in a program:
1. name() - function doesn’t require an argument
2. name(argument) - function requires one argument
3. name(argument1, argument2, …, argumentN) - function requires more than one argument.
Sometimes a function returns data at the end of its task(s). For example, if we desire the square root of 9,
a function that calculates it will require the value 9 (argument) and will return 3 (result of the
calculation).
A lot of functions will be encountered going forward and at some point along the way, the way our own
functions can be created will be explored later.

DATA TYPES
Everything done in programming involves data of one type or another, and functions that manipulate them.
Some of the types of data available in Python are presented below.

INTEGRAL TYPES
These are data types represented in the machine by whole numbers (integers). There are two of these in int,
and bool.

int
Whole numbers which are either binary (base 2), octal (base 8), decimal (base 10 – default), or hexadecimal
(base 16). Important points to note include:
1. binary numbers are started with 0b or 0B e.g. 0b11011, 0B11101 etc.
2. octal numbers are started with 0o e.g. 0o3452, 0o75342 etc.
3. hexadecimal numbers are started with 0x or 0X, and can have the alphabets in them in either case
(upper, lower or mixed) e.g. 0x12ae, 0x2A, 0X12Fb, 0X299AB etc.
4. decimal numbers aren’t preceded by any alphanumeric combination like the others e.g. 234, -234, 87
etc.
The maximum size of an integer is determined only by the amount of memory available in the machine.

bool
These are Boolean values from logic. There only two and these are True (treated as 1 internally) and False
(treated as 0 internally). A special relationship that exist between bool and other data types will be
presented later.

FLOATING-POINT TYPE
These refer to fractional numbers known as double-precision floating-point numbers. Below are some of the
data types in this category. Internally floating-point numbers are stored by the computer/machine using base
2. The consequence of this is that, some floating-point numbers get saved exactly as they are, while others
are saved in an approximate form. The consequence of this is that, it is difficult comparing floating-point
numbers for equality.

float
Numbers of this type are written with the decimal point e.g. 1.0, -2.3 etc.; or in exponential notation with
letter e or E (standard form from mathematics) e.g. 2e9 (2 x 109), 8.9e-4 (8.9 x 10-4), -4.5e-5 (-4.5 x 10-5)
etc.

complex
Values of this type are complex numbers constituted of two floating-point numbers, with the first
representing the real part and the second which is followed closely by letter j or J, represents the complex
part e.g. 2.3 – 4.5j, -1.2e-3 + 4.5J etc.

STRINGS
A string refers to a sequence of 0 or more UNICODE characters. The data type for strings in Python is str.
Unicode refers to the name of a system/scheme used for encoding characters (both those found and not found
on a keyboard). Some important facts to note about strings include:
1. They are marked with single, double, or triple quotes. A triple quote is made up of 3 single or
double quotes. For example: ‘Hello’, “Good morning”, ‘‘‘Good morning’’’, “““Good evening””” etc.

COURSE INSTRUCTOR: T. MIEBI


2. When a string contains no character (0 characters) it is called an EMPTY STRING.
3. A string marked with double quotes can contain single quotes as characters in the string e.g.
“Python’s complexity”
4. A string marked with single quotes can also contain double quotes as characters in the string e.g.
‘“Good morning”, he said’
5. A string marked with triple quotes can contain both single and double quotes as characters in the
string e.g. ‘‘‘“Good morning”, was Peter’s first comment.’’’
6. A string marked with triple quotes can span multiple lines e.g.
‘‘‘Hello everyone. This is our first meeting.
I sincerely hope for fruitful deliberations.’’’
It is possible to get the data type of any value using the function type(argument). The argument for the
function is the value itself. Below are commands and returned results to illustrate this:
>>> type(45)
<class 'int'>

>>> type(0b1101)
<class 'int'>

>>> type(0xAA)
<class 'int'>

>>> type(2.3e-4)
<class 'float'>

>>> type(1.0)
<class 'float'>

>>> type(True)
<class 'bool'>

>>> type(False)
<class 'bool'>

>>> type('')
<class 'str'>

>>> type("Hello")
<class 'str'>

>>> type('''First line.


Second line.''')
<class 'str'>

>>> type("""First line.


Second line.""")
<class 'str'>

NAMING AND SAVING DATA


Data used in a program is either written as part of the program (literal) or supplied by the user.
Irrespective of how it is obtained the fact that it is already a part of the program will make the machine
store it in memory in what is called a VARIABLE. In order to ease subsequent access to the data, the storage
location (data/variable) has to be given a name/identifier. This naming is done with the ASSIGNMENT OPERATOR
(=). The format for this is: name = data
For example: matNo = ‘UG/19/2462’
forename = “Akpoebi”
fullname = “James Peters”
cgpa = 4.99

With this relationship the name automatically produces the data. Try this on console:
>>> fullname = ‘James Peters’
>>> fullname
COURSE INSTRUCTOR: T. MIEBI
Output displayed from this command is
‘James Peters’

In some occasions, it may be necessary to perform multiple assignments. The format for such is given below:
name1, name2, …, nameN = data1, data2, …, dataN
For example:

>>> forename, surname, cgpa = ‘James’, ‘Peters’, 4.99


>>> forename
‘James’
>>> surname
‘Peters’
>>> cgpa
4.99

Another important thing to note is that a single value (data) can be tied to multiple names. This is as
shown below:
>>> a = 47
>>> b = a
>>> a
47
>>> b
47

b = a does not mean there are two values of 47 in memory, it is just one value with two names => a, and b.
This possibility opens the door to a situation that may seem tricky. Consider the commands below:
>>> a = 47
>>> b = a
>>> a = 50

What data/value is b referring to, 47 or 50?


b = a simply implies that b and a are now both referring to 47. a = 50 says a has switched allegiance to 50.
This has nothing to do with b, hence it is still referring to 47, as can be confirmed with results of the
command below:
>>> b
47

It is also possible for names to swap the values they are referring to in one statement (command). This is
as illustrated below:
>>> a = 7; b = 10
>>> a
7
>>> b
10

The next command does the swap


>>> a, b = b, a
>>> a
10
>>> b
7

If a value which used to be tied to a name, later becomes a value with no name referring to it
(anonymous/nameless), it becomes what is called GARBAGE which gets deleted internally to free up memory.
Consider the scenario below:
>>> a = 48; b = 50
>>> a = b (a should reference 50)

COURSE INSTRUCTOR: T. MIEBI


The last command will make 48 garbage because not available name reference it. Simply put nameless data =>
garbage.

DISPLAYING DATA
The function to use for this is: print(list of arguments). Facts about this function, worthy of note include:
1. It takes 0 or more arguments i.e. print() is valid => no argument.
2. Multiple arguments are separated by comma(s) i.e. print(arg, arg, arg, …, arg)
3. The arguments can below to the same or different classes of data. For example: print(“Hello”,
‘everyone’), print(‘CGPA = ’, 4.59) etc.
4. During displaying/printing, a space is displayed after each argument, except the last argument in a
case where there are multiple arguments.
Example
>>> print(‘Hello’, ‘world’)
Hello world
Notice that there’s no space in ‘Hello’, but there’s one after it in the output.
5. Printing is concluded by displaying a new line/line feed (similar to pressing the ENTER-key) by
default.
Example
>>> print(‘Hello’); print(‘World’)
Hello
World
Points 4 and 5 above describe the default behavior of the print() function. Each can be changed by including
an argument with the proper value after all arguments to be displayed.
 Changing the string printed after each argument before the last one (default is
‘ ’), requires using the keyword sep which is assigned the new string to be displayed, as additional
argument i.e. print(arg, arg, …, arg, sep = ‘new string’). The commands and the results below
illustrate this.
>>> print(4, 5)
4 5
>>> print(4, 5, sep = '*')
4*5
 Changing the string (default is new line or ENTER) that gets printed after the last argument requires
the keyword end, which is assigned the new string, as additional argument i.e. print(arg, arg, …, arg,
end = ‘new string’). The commands and results below illustrate this.
>>> print('Hello '); print('Everyone')
Hello
Everyone
>>> print('Hello ', end = ''); print('Everyone')
Hello Everyone
Notice that ‘Everyone’ is displayed on the same line as ‘Hello ’

FORMATTING OUTPUT DISPLAYED


ESCAPE CHARACTER SEQUENCES
The backslash (\) is called the escape character. When it is combined with or precedes another character,
the result is an escape character sequence. It changes the way the character it precedes in a string is
treated or interpreted. Below are some of the escape sequences in Python:
S/N Sequence Meaning and Example
1 \t Tab: It is displayed as a horizontal space which is wider than the regular space.
For example print(‘1\t2’) displays 1 2
2 \n Line feed or New line: It is equivalent to the ENTER key. When it is displayed it
takes the cursor to the next line, thereby ensuring the next data displayed is on a
new line. E.g. print(‘Line 1\nLine 2’) will display:
Line 1
Line 2
3 \\ Backslash: It is used to display the backslash character in a string when it is not
COURSE INSTRUCTOR: T. MIEBI
intended for its usual escape operations. E.g. print(‘11\\11\\2018’) will display
11\11\2018
4 \’ Single quote: It is used to display a single quotation mark in a string marked by
single quotation marks. E.g. print(‘Tom\’s code’) will display Tom’s code
5 \” Double quote: It is used to display a double quotation mark in a string marked by
double quotation marks. For example print(“\“Hello\””) will display “Hello”

FORMATTING WITH F-STRING (PYTHON 3.6 AND HIGHER)


This form of output formatting came with Python and its syntax for specifying how a string is to
be formatted is given as:

f“StringBeingFormatted” or F“StringBeingFormatted”

The string being formatted contains one or placeholders represented by {}. What goes into the
place holder is a value/literal, expected to be a part of the string when it is rendered. A
variable, operation, of a function can also go into a placeholder, since each of these ends up as
a value after been processed or evaluated.
It can also contain a modifier that carries details of how the value is to be formatted. A
modifier, if present, is joined to the value with a colon i.e. {value:modifier}.

Below is a rundown of some of the constituents of a modifier and what they represent or are asking
the system to do.
1. b  Display data in binary format.
f“{7:b}” = 111

2. c  Convert code (integer base of any base) to character


f“{67:c}” = C

3. d  Display data in decimal (base 10) format.


f“{0b111:c}” = 7

4. o  Display data in octal (base 8) format


f“{8:o}” = 10

5. x  Display data in hexadecimal form with lower case alphabets


f“{14:x}” = e

6. X  Display data in hexadecimal form with upper case alphabets


f“{14:X}” = E

7. e  Display data in scientific format with e (lowercase)


f“{23.453:e}” = 2.345300e+01

8. E  Display data in scientific format with E (Uppercase)


f“{23.453:E}” = 2.345300E+01

9. f  Display data as a fractional number


f"{120:f}" = 120.000000

10. F  Display data as a fractional number as well, but with inf and nan from the math module in
uppercase i.e. INF, and NAN.
f"{120:F} {[Link]:F} {[Link]:F}" = 120.000000 NAN INF

11. g  display data with same format as e or f depending on the value. g ≡ e, if the power of
the value in standard/scientific form is less than -4 or greater than +5, otherwise g ≡ f.
f"{1e-4:g}" = 0.0001
f"{1e+5:g}" = 100000
f"{1e-5:g}" = 1e-05
f"{1e+6:g}" = 1e+06
COURSE INSTRUCTOR: T. MIEBI
f"{[Link]:g}" = inf

12. G  display data with same format as e or f depending on the value. G ≡ E, if the power of
the value in standard/scientific form is less than -4 or greater than +5, otherwise G ≡ F.
f"{1e-4:G}" = 0.0001
f"{1e+5:G}" = 100000
f"{1e-5:G}" = 1E-05
f"{1e+6:G}" = 1E+06
f"{[Link]:G}" = INF

13. n  display data as a number (integral, fractional, or complex)


f"{45:n}" = 45
f"{{0b11:n}" = 3
f"{2.54:n}" = 2.54
f"{3-6j:n}" = 3-6j

14. %  display data in Percent (multiply value by 100)


f"{0.25:%}" = 25.000000%

15. +  Display the sign of positive numbers


f"{-0.25:+}" = -0.25
f"{0.25:+}" = +0.25

16. ( )Space  Display space to the left of positive numbers, where the minus is standing for
negative numbers.
f"{25: }\n{-25: }"

25
-25

17. ,  use comma as a thousand separator


f"{1000000:,}" = 1,000,000

18. _  use underscore as a thousand separator


f"{1000000:_}" = 1_000_000

19. Integer  Field width or allocated screen space within which to display the data.
f"{23:6}" = 23
That is
2 3

20. <  Align data to the left of an oversized field width (default for strings)
f"#{34:<7}#" = #34 #
f"#{'Hi':<7}#" = #Hi #
f"#{'Hi':7}#" = #Hi #

21. >  Align data to the right of an oversized field width (default for numbers).
f"#{34:7}#" = # 34#
f"#{34:>7}#" = # 34#

22. ^  Align data to the center of an oversized field width.


f"#{34:^7}#" = # 34 #

23. =  Move the sign to the leftmost position of the field width
f"#{34:+7}#" = # +34#
f"#{-34:+7}#" = # -34#

f"#{34:=+7}#" = #+ 34#
f"#{-34:=+7}#" = #- 34#

COURSE INSTRUCTOR: T. MIEBI


Note
A single character appearing before either <, >, ^, or = represents a fill character that is
used to fill excess space in the oversized field width.
f"#{-34:*<12}#" = #-34*********#
f"#{-34:*<12}#" = #*********-34#
f"#{-34:*<12}#" = #****-34*****#
f"#{-34:*=12}#" = #-*********34#

24. .Integer  Precision


In the absence of f, e, g, F, E, or G in the modifier, precision is taken as number of
significant digits. The value in this case must be fractional to avoid syntax errors.
f"{23.56547:.3}" = 23.6
f"{23.56547:.4}" = 23.57

In the presence of f, e, g, F, E, or G in the modifier, precision is taken as number of


decimal digits.
f"{23.56547:.3f}" = 23.565
f"{23.56547:.4f}" = 23.5655

OUTPUT FORMATTING WITHOUT F-STRING (BEFORE PYTHON 3.6)


Key points to mention when doing formatting this way, include:
1. Syntax: [Link](values)
2. A placeholder inserted into the string being formatted is still represented by {}.
3. It can be empty
Example: "{} x {} = {}".format(2, 3, 2*3)  2 x 3 = 6

It can contain a numeric index in a scenario where the order of the values doesn’t match that of
the placeholders in the string. The index values uniquely identify the values in the format
function. Index values start from 0 for the first (leftmost value) in the format function,
increases by 1 for each as we move rightward.
"{2} x {1} = {0}".format(2*3, 3, 2)  2 x 3 = 6

It can contain a named index. The names making the indexes get assigned their values in the
format-function.
"Code: {c}, Units: {u}".format(c="CMP102", u=4)  Code: CMP102, Units: 4

It can also contain a modifier, with or without the indexes. Modifiers are exactly the same as the
modifiers used in f-string formatting, and must be preceded by the colon (:), in order to
differentiate them from names the of indexes.
"{:b}".format(7)  111
"#{:+7}#".format(34)  # +34#
"#{:=+7}#".format(-34)  #- 34#
"#{:*<12}#".format(-34)  #-34*********#

ARITHMETIC OPERATORS
Operators that go with two values (operands) are said to be binary, while those that go with just one are
said to be unary. The operand of an operator can be: a literal (value in a program), variable (identifier
tied to a literal or value), or a function that returns a value. The table contains the basic arithmetic
operators.
Symbol Name/Meaning Example
+ Addition 34 + 2 = 36
- Subtraction 5 – 2.5 = 2.5
* Multiplication 6.0 * 3 = 18.0
/ Float division 9 / 4 = 2.25, 5.0 / 2 = 2.5

COURSE INSTRUCTOR: T. MIEBI


// Integer division 9 // 4 = 2, 5.0 // 2 = 2.0
** Exponentiation 4 ** 2 = 42 = 16, 16 * 0.5 = 4.0
% Modulus/Remainder 9 % 4 = 1, 6 % 3 = 0, 5.8 % 2 = 1.7999999999999998, 3 % 4 = 3
Note
Before reaching the point where strings will be treated in details it is important to point out that two
arithmetic operators have a very special tie with strings. These are:

1. + (concatenation) – refers to joining a string to another string to form a new string. If a value is
not a string, then it has to be converted to string. How this is done is a topic not far away.
For example: ‘CGPA: ’ + ‘4.49’ = ‘CGPA: 4.49’
2. * (Repetition) – concatenating multiple versions of a given string. The operator takes a string and
an int representing the number of repetitions.
For example: ‘*’ * 6 = ‘******’

ARITHMETIC OPERATOR PRECEDENCE


The above topic concerns the order in which arithmetic operators are used in evaluating an arithmetic
expression with several operators. The order in which they are to be used for the evaluation is given below:
 1st: ** (Exponentiation)
 2nd: *, /, //, % (with several of these, evaluate one by one from left to right)
 3rd: +, - (with several of these, evaluate one by one from left to right)

Irrespective of the above order, arithmetic expressions in brackets must be resolved first following the
above order, before resolving the resulting main expression.
The knowledge of operator precedence helps in writing simpler looking arithmetic expressions, without
relying heavily on brackets.
Examples
Brackets will be used to indicate which operator is in use, until there is just one.
1. 5 * 4 // 2 + 10 – 5 % 3 – 7 + 2 ** 3
(5 * 4) // 2 + 10 – 5 % 3 – 7 + 2 ** 3
(20 // 2) + 10 – 5 % 3 – 7 + 2 ** 3
10 + 10 – (5 % 3) – 7 + 2 ** 3
10 + 10 – 2 – 7 + (2 ** 3)
(10 + 10) – 2 – 7 + 8
(20 – 2) – 7 + 8
(18 – 7) + 8
11 + 8 = 19
2. 5 + 5 / 2 – 4 // 3 + (12 – 10 * 2 % 3) - 8 % 3 + 7
5 + 5 / 2 – 4 // 3 + (12 – (10 * 2) % 3) - 8 % 3 + 7
5 + 5 / 2 – 4 // 3 + (12 – (20 % 3)) - 8 % 3 + 7
5 + 5 / 2 – 4 // 3 + (12 – 2) - 8 % 3 + 7
5 + (5 / 2) – 4 // 3 + 10 - 8 % 3 + 7
5 + 2.50 – (4 // 3) + 10 - 8 % 3 + 7
5 + 2.50 – 1 + 10 – (8 % 3) + 7
(5 + 2.50) – 1 + 10 – 2 + 7
(7.50 – 1) + 10 – 2 + 7
(6.50 + 10) – 2 + 7
(16.50 – 2) + 7
14.50 + 7 = 21.50

AUGMENTED ASSIGNMENT OPERATORS


These operators are needed when the value (initial) in a variable is to be used in an arithmetic operation
that produces another value (result), and the result is to be assigned to the variable. For example, sum =
sum + 6.
Presented below are the augmented operators:
1. a = a + b => a += b
2. a = a – b => a -= b

COURSE INSTRUCTOR: T. MIEBI


3. a = a * b => a *= b
4. a = a / b => a /= b
5. a = a ** b => a **= b
6. a = a // b => a //= b
7. a = a % b => a %= b

MATH FUNCTIONS
Using mathematical functions requires importing the content (function/data) of the math module. How this is
done and module content used are illustrated below:
1. Importing => import math
Using content => [Link](argument, …), [Link](), or [Link]

2. Importing => from math import *


Using content => function(argument, …), function(), or data.

The second approach is preferable, because it ensures we use less characters by avoiding math, thus saving
us valuable time. Presented below are some of the content of the math module.
1. sqrt(x) => � ≥ 0 (positive root)
2. trunc(x) => Returns integer part of a floating-point number e.g. [Link](3.5) = 3
3. pi => π (3.1415926535897931)
4. pow(x, y) => xy
5. log(x) => returns natural logarithm of x (logarithm to base e)
6. log10(x) => returns the logarithm of x to base 10 i.e. log x, or log10 x
7. log(x, base) => returns the logarithm of x to the base specified.
8. e => it is equivalent to the constant e = 2.1782818284590451
9. exp(x) => returns ex (natural antilogarithm x).
10. fabs(x) => returns the absolute value of x in floating-point form
11. ceil(x) => returns the lowest integer that is greater than or equal to x. It is denoted
mathematically as �
12. floor(x) => returns the highest integer lesser than or equal to x. It is denoted
mathematically as �
13. factorial(x) => returns x! (x factorial)
14. fmod(x, y) => returns x % y as a floating-point number
15. hypot(x, y) => returns �2 + �2
16. degrees(x) => Returns x radians converted to degrees (180x / π)
17. radians(x) => Returns x degrees converted to radians (πx / 180)
18. sin(x) => returns sine of x radians
19. cos(x) => returns cosine of x radians
20. tan(x) => returns tangent of x radians
21. asin(x) => returns sin-1 x (inverse sine of x) in radians
22. acos(x) => returns cos-1 x (inverse cosine of x) in radians
23. atan(x) => returns tan-1 x (inverse tangent of x) in radians
24. sinh(x) => returns the hyperbolic sine of x radians i.e. sinh(x)
25. cosh(x) => returns the hyperbolic cosine of x radians i.e. cosh(x)
26. tanh(x) => returns the hyperbolic tangent of x radians i.e. tanh(x)
27. asinh(x) => sinh-1(x)
28. acosh(x) => cosh-1(x)
29. atanh(x) => tanh-1(x)

It is also possible to make everything (data and functions) in the module available by using the import
format above. This is done by using * (wild character), and it is as shown below:
from moduleName import *

Some functions for mathematical operations are not in the math module, hence their usage doesn’t require
importing the math module. Some of these are:
1. abs(x) => |x| i.e. the absolute value of x returned in the same data type as x. For example abs(-
4.3) = 4.3, abs(-4) = 4, abs(-4.0) = 4.0
COURSE INSTRUCTOR: T. MIEBI
2. pow(x, y) => xy e.g. pow(2, 5) = 35, pow(2.0, 5) = 32.0, pow(2, 2.5) = 32.0
Notice that the result is fractional if there is a fractional argument provided, but integer if there
is none.
3. round(x, n) => returns x, rounded to n decimal places. E.g. round(2.4659, 2) = 2.47, round(-
0.025479, 2) = -0.25

DATA CONVERSION
Internally, a Boolean value is numeric with True = 1, False = 0. When the operands (numeric) of an operator
are of different types, one gets converted to the type of the other before the expression the is resolved to
get a result.
 Implicit conversion of numeric values takes the order: bool => int => float. It is clear that the
bool is the lowest in the hierarchy. The rule for the conversion is that the lower type in the
hierarchy gets converted to the higher. For example:
1.0 + 1 = 2.0, 1 + 1 = 2, True + False = 1, True + 2.0 = 3.0, 2 ** False = 1 etc.
 Explicit conversion is the scenario where functions are used to force the conversion of one type of
data to another. Below are functions some functions for this:
1. int(argument): it returns an int value from the provided argument which can be of type/class:
i. str: a string in integer form gets converted to the actual integer value.
>>> int(‘4’)
4
>>> int(“6”)
6
ii. float: floating-point value gets truncated (cut off the fractional part).
>>> int(2.56)
2
>>> int(4.34)
4
iii. bool: value of type bool gets converted to its numeric equivalent.
>>> int(True)
1
>>> int(False)
0

2. bin(argument): returns the binary form of its argument (integer) as a string.


>>> bin(45)
'0b101101'
>>> bin(0o567)
'0b101110111'
>>> bin(0xa1)
'0b10100001'.

3. oct(argument): returns the octal form of its argument (integer) as a string.


>>> oct(16)
'0o20'
>>> oct(0b1101)
'0o15', oct(0xaa) = '0o252'.

4. hex(argument): returns the hexadecimal form of its argument (integer) as a string.


>>> hex(31)
'0x1f'
>>> hex(0o20)
'0x10'
>>> hex(0b1111)
'0xf'.

5. float(argument): converts its argument to a fractional/floating-point number. The argument can be


of type:
COURSE INSTRUCTOR: T. MIEBI
i. int: the floating-point equivalent of the int value is returned.
>>> float(1)
1.0
ii. str: the floating-point form of the string which is either in the form of an int or
float. >>> float(‘4’)
4.0
>>> float(“2.5”)
2.5
iii. bool: the function returns the numeric equivalent of the Boolean value in floating-point
form. >>> float(True)
1.0
>>> float(False)
0.0

6. bool(argument): converts the provided argument to either True or False. The argument can be of
type/class
i. numeric(int or float): it will return False if the number is 0 or 0.0 and True otherwise.
>>> bool(0.0)
False
>>> bool(2.5)
True
>>> bool(-4)
True
>>> bool(0)
False
ii. str: a string is False if it is empty, otherwise it is True.
>>> bool(‘’)
False
>>> bool(“”)
False
>>> bool(‘ ’)
True
>>> bool(“Hi”)
True.

7. str(argument): converts it argument which can be numeric or Boolean to a string.


>>> str(4)
‘4’
>>> str(2.3e3)
‘2300.0’
>>> str(True)
‘True’
>>> str(False)
‘False’.

8. eval(argument): The supplied argument must be a string which is either numeric or represents an
arithmetic expression which could carry 0 or more mathematical functions. It returns a single
numeric value which represents the numeric string or the result of the entire arithmetic
expression in string forms. For example:
i. >>> eval(‘4’)
4
ii. >>> eval(‘2.5’)
2.50
iii. >>> eval(‘2,5e4’)
25000.0
iv. >>> eval(‘[Link](3 ** 2 + 4 ** 2)’)
5.0 => 32 + 42
COURSE INSTRUCTOR: T. MIEBI
The eval() function produces an error if the numeric a numeric string provided has leading zeros
(one or more zeros before a non-zero digit) e.g. eval(‘033’), eval(‘2 + 02.4’) etc.

Note: All of the functions above will generate errors (also known as EXCEPTIONS), if the conversion fails,
which can be mainly due to the type of argument supplied. Management of such errors/exceptions is a topic of
its own for another day.

COMMENTS
These are explanatory notes added to a program to explain to the writer or another programmer (maybe
employed to maintain the program) what a program statement or group of statements represent or does.
Comments are not interpreted by the machine; after all they are for humans (programmers). Comments are
started by # followed by a space i.e. # comment
Examples
>>> print(“Hello”); print(“there”)
Hello
there

>>> print(“Hello”); # print(“there”)


Hello

SOLVED PROBLEMS
Presented below are problems requiring solutions in the form of programs. The output of each program is also
presented as proof, that it indeed solves the problem it is meant for. Comments are used extensively to
explain the logic of each programming solution.

1. Write a program that displays the area and perimeter of a circle that has a radius of 5.5 using the
following formula:
perimeter = 2 x radius x π
area = radius x radius x π
Program
# Store value for radius
radius = 5.5

# Import math module to access value for PI


import math

# Calculate & store perimeter


perimeter = 2 * radius * [Link]

# Calculate & store area


area = radius * radius * [Link]

# Display perimeter & area


print("Perimeter =", perimeter)
print("Area =", area)

Output

Note: You encouraged to and verify by solving manually, and this should be done wherever possible.
Furthermore, some development tools (IDE’s), give warning when import statements appear below non-import
statements in a program.

2. Assume a runner runs 14 kilometers in 45 minutes and 30 seconds. Write a program that displays the
average speed in miles per hour. (Note that 1 mile is 1.6 kilometers.)

Program
# Save distance ran in miles

COURSE INSTRUCTOR: T. MIEBI


# Number of 1.6km in 14km = Number of miles in 14km
distance = 14 / 1.6;

# Save time taken in hours


# Number of 60mins in 45mins = Number of hours in 45mins
# Number of (60 x 60)secs in 30secs = Number of hours in 30secs
time = 46 / 60 + 30 / (60 * 60)

# Calculate & save average speed


avgSpeed = distance / time

# Display average speed


print("Average speed =", avgSpeed)

Output

PRACTICE EXERCISES (SET 1)


1. The U.S. Census Bureau projects population based on the following assumptions:
 One birth every 7 seconds
 One death every 13 seconds
 One new immigrant every 45 seconds
Write a program to display the population for each of the next five years. Assume the current
population is 312,032,486 and one year has 365 days.

Expected Output
Population after year 1: 314812582
Population after year 2: 317592678
Population after year 3: 320372774
Population after year 4: 323152870
Population after year 5: 325932966tion

2. Assume a runner runs 24 miles in 1 hour, 40 minutes, and 35 seconds. Write a program that displays the
average speed in kilometers per hour. (Note that 1 mile is 1.6 kilometers.)

Expected Output
Average speed: 22.906379453189732

RECEIVING DATA FROM THE KEYBOARD


The source of data in this instance is the keyboard. The function used for the task is input(). The function
may take a string as argument. The string argument represents the prompt (message to the user requesting
data entry) to the user. The function returns what is typed from the keyboard as a string data.
Points to note include:
1. The function (when operational) makes the cursor blink after the prompt (if any) has been displayed.
The blinking cursor provides the user the opportunity type in the data.
2. If the data expected is not supposed to be a string, then it can be converted to the desired data
type with the appropriate function.
3. The process of receiving data to be converted can be broken into two distinct parts which are:
i. Receive and store the string version
ii. Convert and save it to the desired data type
This is as illustrated by the statements below:
str = input(‘Enter an integer’) #receive and store the string
numb = int(str) #convert string to int

Two processes can also be combined into one statement, by making the received string anonymous i.e.
not giving it a name. The idea is to pass input() as argument to the function doing the conversion.
The two statement are combined below to illustrate this:
numb = int(input(‘Enter an integer’))

COURSE INSTRUCTOR: T. MIEBI


It is best to do the receiving and conversion of the string data in one line, to avoid forgetting to
convert, that may lead to errors emanating from using the wrong data type.

RECEIVING MULTIPLE NUMBERS


USING eval(string)
The eval() function can receive a string made of multiple numbers separated by comma(s) and save them in an
equivalent number of comma-separated variables i.e. var1, var2, …, varN = eval(‘d1, d2, …,dN’)
This therefore makes it possible to receive and save multiple values separated by comma(s) in a single
statement. For this function to work, the separation must be with commas. The string can be a string value
or any other python expression that can be resolved into a string. For this case, however, the string value
is coming from the keyboard via the function, input(…).
Example
a, b = eval(input('Enter two integers separated by comma: '))
print(a, b)

Output
Enter two integers separated by comma: 3, 4
3 4

USING map(dataType, [Link](separator))


This is an alternative to eval(). It
1. Splits the string into the separate parts, using the separator specified. If there is no separator
provided, it uses space.
2. Converts each to the data type specified
3. Finally saves them in the comma-separated list of variables.
With map(), there is greater versatility since we have the option of using different separators, as well as
final data type obtained. The string just like eval(), can also come from a string value, or any expression
(variable or function) that can be resolved into a string.

Example 1 (Comma-separted)
strData = input('Enter two integers separated by comma: ')
a, b = map(float, [Link](“,”))
print(a, b)

Output
Enter two integers separated by comma: 3, 4
3.0 4.0

Example 2 (Space-separated)
strData = input('Enter two integers separated by space: ')
a, b = map(float, [Link]())
print(a, b)

Output
Enter two integers separated by comma: 3 4
3.0 4.0

Example 3
strData = input('Enter two integers separated by space: ')
a, b = map(complex, [Link]())
print(a, b)

Output
Enter two integers separated by comma: 3 4
(3+0j) (4+0j)

COURSE INSTRUCTOR: T. MIEBI


SOLVED PROBLEMS
1. The program below is meant to calculate the volume of a cylinder with values of diameter and height
supplied by the user in response to displayed prompts.
Solution
# Import math to access pi
import math

# Prompt for and save diameter entered


diameter = float(input("Enter diameter: "))

# Prompt for and save height


height = float(input('Enter height: '))

# Calculate and save volume


volume = [Link] * diameter ** 2 * height / 4

# Display calculated volume separated by a line space


print()
print('Volume of the cylinder =', volume);

Output
Enter diameter: 2.5
Enter height: 6.5

Volume of the cylinder = 31.906800388021338

2. Write a program that prompts the user to enter the length from the center of a pentagon to a vertex
and computes the area of the pentagon, as shown in the following figure.

3 3 2
The formula for computing the area of a pentagon is ���� = 2
� , where s is the length of the side. The side

can be computed using the formula � = 2� sin 5, where r is the length from the center of a pentagon to a vertex.
Here is a sample run:

Solution
# Import math module for math functions used
import math

# Prompt for and save r


r = float(input('Enter the length of the center to a vertex: '))

# Calculate and save s


s = 2 * r * [Link]([Link] / 2)

# Calculate and save area


area = 3 * [Link](3) * s ** 2 / 2

# Display caculated area to 2 decimal places


print('The area of the pentagon is', round(area, 2))

Output

COURSE INSTRUCTOR: T. MIEBI


3. Write a program that prompts the user to input a four-digit positive integer. The program then
outputs the digits of the number, one digit per line. For example, if the input is 3245, the output
is:
3
2
4
5

Solution
# Request for and save 4-digit interger
numb = int(input('Enter a 4-digit integer: '))

# Get 1st digit


digit = numb // 1000

# Display 1st digit


print(digit)

# Get remaining digits


numb = numb % 1000

# Get 2nd digit


digit = numb // 100

# Display 2nd digit


print(digit)

# Get remaining digits


numb = numb % 100

# Get 3rd digit


digit = numb // 10

# Display 3rd digit


print(digit)

# Get remaining digit = 4th digit


numb = numb % 10

# Display 4th digit


print(numb)

Output

PRACTICE EXERCISES (SET 2)


1. Write a program that reads in the radius and length of a cone and computes the base area and volume
to 4 decimal places each, using the following formulas:
area = radius * radius * π
volume = area * length / 3
Here is a sample run:

2. How cold is it outside? The temperature alone is not enough to provide the answer. Other factors
including wind speed, relative humidity, and sunshine play important roles in determining coldness
COURSE INSTRUCTOR: T. MIEBI
outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to
measure the coldness using temperature and wind speed. The formula is given as follows:

��� = 35.74 + 0.6215�� − 35.75�0.16 + 0.4275�� �0.16

where ta is the outside temperature measured in degrees Fahrenheit and v is the speed measured in
miles per hour. twc is the wind-chill temperature. The formula cannot be used for wind speeds below 2
mph or for temperatures below -58oF or above 41°F.
Write a program that prompts the user to enter a temperature between -58oF and 41°F and a wind speed
greater than or equal to 2 and displays the wind-chill temperature. Here is a sample run:

3. Write a program that prompts the user to enter the three points (x1, y1), (x2, y2), and (x3, y3) of a
triangle and displays its area. The formula for computing the area of a triangle is
side = (�� − �� )2 + (�� − �� )2
s = (side1 + side2 + side3) / 2
area = �(� − ����1)(� − ����2)(� − ����3)
Here is a sample run:

mport math

RELATIONAL OPERATORS
These operators are used to compare values (operands). The result of the comparison is either True or False.
Relational operators are of two types which are: comparison and equality operators.
Operator Reads as Example
> Is greater than 5 > 4 = True, 6 > 12 = False
>= Is greater than or equal to 6 >= 4 = True, 4 >= 4 = True, 7 >= 12 = False
< Is less than 4 < 6 = True, 4 < 1 = False
<= Is less than or equal to 5 <= 6 = True, 7 <= 7 = True, 8 <= 4 = False
== Is equal to 4 == 4 = True, 6 == 2 = False
!= Is not equal to 4 != 2 = True, 4 != 4 = False
>, >=, <, and <= constitute the comparison operators, while == and != constitute the equality operators.

LOGICAL OPERATOR
The operands and result of these operators are all of type bool. There are three of these operators, which
are: and, or, and not.
and
1. It is binary (takes two operands)
2. Result is False if at least one operand is False, otherwise result is True. Result determination is
as follows:
i. Its operands are checked one after the other from left to right
ii. Checking of operands get halted as soon as the first False operand is encountered (search for
1st False)
iii. The first False value encountered is always returned as result. If there is no False value,
then the last True value is returned as result.
Examples
1. >>> True and False
False
2. >>> True and 3.5
3.5
3. >>> 0 and False
0
4. >>> 1 and ‘H’ and True and 2.5
2.5
COURSE INSTRUCTOR: T. MIEBI
5. >>> 4 and True and ‘’ and 0
‘’

or
1. It is binary
2. Result is True is at least one operand is True, otherwise result is False
Result determination is as follows:
i. Values are checked one after the other, from left to right.
ii. Further check is halted when the 1st True operand is encountered.
iii. The first True value encountered is always returned as result. If there is no True operand,
then the last False operand is returned as result.
Examples
1. >>> 4 or 2.6 or ‘’
4
2. >>> False or 0.0 or 0
0
3. >>> ‘’ or 0.001 or True or “”
0.001
4. >>> ‘’ or True or 4 or False
True

NOTE: This evaluation in which further check/evaluation is halted when the first True (for or) or the first False (for
and) has been encountered, is called SHORT-CIRCUIT EVALUATION.

not
It is a unary operator that toggles the value of its Boolean operand, by changing True (or its equivalent in
other data types) to False, and False (or its equivalent in other data types) to True. Its result are only
Boolean values i.e. True or False, unlike the above Boolean operators.
Examples
1. >>> not ‘’
True
2. >>> not 0
True
3. >>> not 1.2
False
4. >>> not True
False
in
This operator is called the membership operator. It returns True if the left operand (single data) can be
found in left operand (a sequence collection of data). It returns False otherwise.
Examples
1. >>> ‘a’ in ‘abba’
True
2. >>> ‘e’ in ‘abba’
False
3. >>> ‘mth’ in (‘mth’, ‘phy’, ‘chm’)
True
4. >>> 4 in (1, 2, 3)
False

This operator can also be used with the operator not.


1. >>> ‘a’ not in ‘abba’
False
2. >>> ‘e’ not in ‘abba’
True

Notice that the single value on the left and the individual values making the group of values on the right
of the operator are the same.
COURSE INSTRUCTOR: T. MIEBI
OPERATOR PRECEDENCE REVISITED
With the introduction of both the relational and logical operators, it is only proper to revisit operator
precedence.
1. () (Operators in the bracket must be evaluated first) ----------------------------- Highest precedence
2. +, - (Unary plus, and minus)
3. ** (Exponentiation)
4. not
5. *, /, //, %
6. +, - (Binary addition & subtraction)
7. <, <=, >, >= (Comparison)
8. ==, != (Equality)
9. and
10. or
11. =. +=, -=, /=, //=, %=, *= (Assignment operators) --------------------------------- Lowest precedence
Note
1. Precedence is decreasing downward, i.e. those listed as (1) have the highest precedence hence will
always be treated first, while those listed against (10) have the lowest precedence hence will always
be evaluated last.
2. When dealing with more than one operator with the same precedence level, evaluation is from the
leftmost operator to the rightmost one.

Examples
Note: The operator in the expression been evaluated is underlined

1. (1 + 3 - 6 * 2 ** 2) + 9 - 4 // 8 % 2
(1 + 3 – 6 * 4) + 9 – 4 // 8 % 2
(1 + 3 – 24) + 9 – 4 // 8 % 2
(4 – 24) + 9 – 4 // 8 % 2
-20 + 9 – 4 // 8 % 2
-20 + 9 – 0 % 2
-20 + 9 – 0
-11 – 0
-11

2. 2 * 2 – 3 > 2 and 4 – 2 > 5


4 – 3 > 2 and 4 – 2 > 5
1 > 2 and 4 – 2 > 5
1 > 2 and 2 > 5
False and 2 > 5
False and False
False

3. 2 ** 3 – 3 < 2 or 7 % 3 and 5 // 4
8 – 3 < 2 or 7 % 3 and 5 // 4
8 – 3 < 2 or 1 and 5 // 4
8 – 3 < 2 or 1 and 1
5 < 2 or 1 and 1
False or 1 and 1
False or 1
1

BRANCHING/DECISION MAKING
All the programs that have been written thus far, including those given in the exercises are written or to
be written in ways that ensure all statements are interpreted and executed.
The time has come to learn techniques that will enable us instruct a machine to decide whether or not to
interpret and execute certain statements in our programs. At the center of it all is a relational or logical

COURSE INSTRUCTOR: T. MIEBI


expression (expression that returns a value considered True or False) called a CONDITION. The available
decision-making statements are now examined below:

if Statements
if condition:
execute statement 1
execute statement 2
:
execute statement N

The statement above simply means that, if the condition is True, execute all indented statements under
(Statements 1, 2, …, N). The statements must all be indented with the same amount of space.
The program below is meant to calculate and display the area of a circle only if its radius is at least 0.
It should display an error message otherwise.

Code
import math

radius = float(input('Enter radius: '))

if radius >= 0:
area = [Link] * radius * radius
print('Area of circle is', area)

if radius < -1:


print('Error!!! Radius cannot be negative.')

Run 1
Enter radius: 4.5
Area of circle is 63.61725123519331

Run 2
Enter radius: -2.4
Error!!! Radius cannot be negative.

if-else Statements
In this case statement(s) are in two sets. The first set is to be executed if the condition is True, while
the second set which comes after the keyword else, is to be executed if the condition is False. The
structure is as given below:

if condition:
statement 1
statement 2
:
statement N
else:
statement 1
statement 2
:
statement N

The program that was written earlier can be written in such a way that the two if-statements can be replaced
with a single if-else statement. This is presented below:

Code
import math

radius = float(input('Enter radius: '))

if radius >= 0:
area = [Link] * radius * radius
COURSE INSTRUCTOR: T. MIEBI
print('Area of circle is', area)
else:
print('Error!!! Radius cannot be negative.')

if-elif-else Statement
This is considered when there are multiple conditions and for each condition that is true, there are
statements to be executed. During execution, conditions are tested one after the other. If a condition is
True, the indented statements immediately under it are executed, thus ending the execution of the decision-
making statement. This is because conditions under the one that is True (if available) are not be tested,
since the whole exercise is a search for the first True condition from top to bottom. Syntax is given below:

if condition:
Statement(s)
elif condition:
Statement(s)
elif condition:
Statement(s)
:
else:
Statement(s)
Note
1. if => 1
2. elif => 1 or more
3. else => 0 or 1 (provided if there must be a true condition, and it is possible for all conditions
but the last (which has to be True) to be false.)
Example
The program below displays the correct grade for a score entered by the user in response to a system prompt.

Code
score = int(input('Enter score: '))

if score < 45:


print('Grade is F')
elif score < 50:
print('Grade is D')
elif score < 60:
print('Grade is C')
elif score < 70:
print('Grade is B')
else:
# A score must have a grade
print('Grade is A')

Sample Run 1
Enter score: 44
Grade is F

Sample Run 2
Enter score: 69
Grade is B

Sample Run 3
Enter score: 70
Grade is A

SOLVED PROBLEMS
1. The two roots of a quadratic equation, for example, can be obtained using the following formula:

COURSE INSTRUCTOR: T. MIEBI


−�+ �2 −4�� −�− �2−4�� 2
�1 = � =
2�
and �2 = � = 2�
b – 4ac is called the discriminant of the quadratic equation. If it
is positive, the equation has two real roots. If it is zero, the equation has one root. If it is
negative, the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays the result based on
the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display
one root. Otherwise, display The equation has no real roots. Here are some sample runs.
Enter a, b, c: 1.0, 3, 1
The roots are -0.381967 and -2.61803

Enter a, b, c: 1, 2.0, 1
The root is -1

Enter a, b, c: 1, 2, 3
The equation has no real roots
Code
import math

# Prompt for, receive and save the values of a, b, and c


a, b, c = eval(input('Enter a, b, c: '))

# Calculate discriminant
disc = b * b - 4 * a * c

# Test discriminant
if disc == 0:
# Calculate and display single root
r1 = -b / (2 * a)
print('The root is', round(r1, 5))
elif disc > 0:
# Calculate and display two roots
r1 = (-b + [Link](disc)) / (2 * a)
r2 = (-b - [Link](disc)) / (2 * a)
print('The roots are', round(r1, 5), 'and', round(r2, 5))
else:
print('The equation has no real roots')

2. You can use Cramer’s rule to solve the following system of linear equation:
ax + by = e
cx + dy = f
x = (ed – bf)/(ad – bc)
y = (af – ec)/(ad – bc)
Write a program that prompts the user to enter a, b, c, d, e, and f and displays the result. If ad – bc
is 0, report that The equation has no solution.
Here are some sample runs.

Enter a, b, c, d, e, f: 9.0, 4.0, 3.0, -5.0, -6.0, -21.0


x is -2.0 and y is 3.0

Enter a, b, c, d, e, f: 1.0, 2.0, 2.0, 4.0, 4.0, 5.0


The equation has no solution

Code
a, b, c, d, e, f = eval(input('Enter a, b, c, d, e, f: '))

# Calculate and save disc


disc = a * d - b * c

# Test discriminant
if disc == 0:
print('The equa tion has no solution')
else:
# Calculate x
x = (e * d - b * f) / disc

COURSE INSTRUCTOR: T. MIEBI


# Calculate y
y = (a * f - e * c) / disc

# Display x and y
print('x is', x, 'and y is', y)

PRACTICE EXERCISE (SET 3)


1. Write a program that converts a positive integer into the Roman number system. The Roman number
system has digits
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Numbers are formed according to the following rules:
a. Only numbers up to 3,999 are represented.
b. As in the decimal system, the thousands, hundreds, tens, and ones are expressed separately.
c. The numbers 1 to 9 are expressed as
I 1
II 2
III 3
IV 4
V 5
VI 6
VII 7
VIII 8
IX 9
As you can see, an I preceding a V or X is subtracted from the value, and you can never have more
than three I’s in a row.
d. Tens and hundreds are done the same way, except that the letters X, L, C, and C, D, M are used
instead of I, V, X, respectively.
Your program should take an input, such as 1978, and convert it to Roman numerals, MCMLXXVIII.

2. Write a program that prompts the user to enter a point (x, y) and checks whether the point is within
the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the
rectangle and (6, 4) is outside the rectangle, as shown in the figure below. (Hint: A point is in the
rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical
distance to (0, 0) is less than or equal to 5.0 / 2. Test your program to cover all cases.) Here are
two sample runs:

COURSE INSTRUCTOR: T. MIEBI


3. Write a program that prompts the user to enter a point (x, y) and checks whether the point is within
the circle centered at (0, 0) with radius 10. For example, (4, 5) is inside the circle and (9, 9) is
outside the circle, as shown in the figure below.

(Hint: A point is in the circle if its distance to (0, 0) is less than or equal to 10. The formula
for computing the distance is (�2 − �1)2 + (�2 − �1)2 . Test your program to cover all cases.) Two sample
runs are shown next.

4. Suppose a right triangle is placed in a plane as shown below. The right-angle point is at (0, 0), and
the other two points are at (200, 0), and (0, 100). Write a program that prompts the user to enter a
point with x- and y-coordinates and determines whether the point is inside the triangle. Here are
some sample runs:

COURSE INSTRUCTOR: T. MIEBI


5. Write a program that prompts the user to enter the center x-, y-coordinates, width, and height of two
rectangles and determines whether the second rectangle is inside the first or overlaps with the first,
as shown in the figure below. Test your program to cover all cases.

Here are some sample runs:

LOOPING/ITERATING
This refers to executing a statement or set of statements (normally indented) multiple times (in reality, it
is 0 or more times). The types of looping statements are now treated below:

WHILE LOOP
In this scenario, a statement or group of statements will be executed each time a condition evaluated is
True. Evaluation of the condition continues until it becomes False, at which point the loop ends. The
diagram (flow chart) below describes this.

COURSE INSTRUCTOR: T. MIEBI


Examples
1. Write a program that enters integers and sums and displays both the odd and even integers. The program
should continue reading and processing numbers until it receives a 0.
Solution
# Variables needed
oddSum = 0
evenSum = 0

# Display prompt for data entry


print('Enter integers, with a 0 to stop entry')

# Read first number, just in case 0 is the first


number = int(input())

# While this number is not 0, process it & read others


while number != 0:
# Test through dividing by 2 to know even & odd
if number % 2 == 0:
evenSum = evenSum + number
else:
oddSum = oddSum + number

# Read next number


number = int(input())

# Display output
print() # Newline to push output downward
print('Even numbers entered:', evenSum)
print('Odd numbers entered:', oddSum)

Output
Enter integers, with a 0 to stop entry
2
3
5
6
8
11
-2
-4
0

Even numbers entered: 10


Odd numbers entered: 19
COURSE INSTRUCTOR: T. MIEBI
2. Write a program that reads a positive integer and displays its digits one line at a time, starting with
the unit.
Solution
# Read integer
number = int(input('Enter and integer: '))

while number > 0:


# Print the rightmost digit
print(number % 10)

# get digits remaining


number = number // 10

Output
Enter and integer: 2375050
0
5
0
5
7
3
2

FOR-LOOP
The while-loop is most suitable where continuing with the loop is based on the existence of a condition
because there is no count on how many times the loop should run. The for-loop however is most suitable where
there is an exact number of times to run the loop. The syntax of a for-loop is dependent on a couple on the
function range() which returns a sequence of whole numbers with the range dependent on the supplied
argument(s) which must be integer(s)
1. range(a): sequence of integers in steps of 1, from 0 to (a – 1). E.g. range(5) = 0, 1, 2, 3, 4
2. range(a, b): sequence of integers in steps of 1, from a to (b – 1). E.g. range(1, 7) = 1, 2, 3, 4, 5,
6
3. range(a, b, h): sequence of integers in steps of h, from a to (b – 1) if the sequence is increasing,
or (b + 1) if the sequence is decreasing. Examples are provided below:
i. range(1, 10, 2) = 1, 3, 5, 7, 9
ii. range(10, 6, -1) = 10, 9, 8, 7

The format of the for-loop is now presented below:


for var in range(argument):
statements to execute
The way it works is that values from the sequence returned by rang() are copied into var, one after the
other, and can afterwards be used (if necessary), in the indented statement(s) to be executed repeatedly.
Example
1. for a in range(5):
print(a)
Output
0
1
2
3
4
2. for a in range(1, 7)
print(a)
Output
1
2
3
4
COURSE INSTRUCTOR: T. MIEBI
5
6

3. for a in range(10, 1, -1):


print(a)
Output
10
9
8
7
6
5
4
3
2

BREAKING CONTROL FLOW OF A LOOP


It is possible to either stop a loop from completing its iterations or making the execution of a particular
iteration incomplete.
 break is the keyword that stops further iteration of a loop when executed.
Code 1 (No break)
for h in range(5):
print(h, end = "\t")

Output 1
0 1 2 3 4

Code 2 (break executed)


for h in range(5):
if h > 2:
break
print(h, end = "\t")

Output 2
0 1 2

Notice that from code 2, when h became 3, the break statement was executed, consequently stopping the
loop even though that iteration had not been completed (the print function was yet to be executed).

 continue is the keyword that stops the further execution of an iteration, thereby making it
incomplete
Code
for h in range(5):
if h < 2:
continue
print(h, end = "\t")

Output
2 3 4

Notice that the continue statement was active when h = 0, and 1, consequently preventing the print
statement from been executed. However, the loop was not terminated as can be seen from the displaying
of 2, 3, and 4; when continue was inactive.

Both keywords when executed, affect the loop they are directly under. This is important when dealing with
nested loops.

COURSE INSTRUCTOR: T. MIEBI


NESTED LOOPS
This refers to a scenario where a loop is to be executed under another loop. It is common in problems where
there are multiple sequences, and one sequence depends on the other. For example, in timing, 60 seconds = 1
minute. This means that the second sequence (dependent) will run 60 iterations, for the minute sequence to
run just 1 iteration.
The number of loops to nest, depends on the number of dependent sequences presented in the question. The
outermost loop controls the independent sequence, while each nested loop controls a dependent sequence. If
sequence A depends on 3 sequences, then the loop controlling sequence A, will have 3 loops above it in the
program.
It must also be stated that loops nested, don’t necessarily have to be of the same type.

SOLVED PROBLEMS
1. A cancellation error occurs when you are manipulating a very large number with a very small number.
The large number may cancel out the smaller number. For example, the result of 100000000.0 +
0.000000001 is equal to 100000000.0. To avoid cancellation errors and obtain more accurate results,
carefully select the order of computation. For example, in computing the following series, you will
obtain more accurate results by computing from right to left rather than from left to right:
1 1 1
1+ + +…+
2 3 �
Write a program that compares the results of the summation of the preceding series, computing both
from left to right and from right to left with n 50000.
Solution
 The series is a sum of reciprocals from 1 to n
 Numbers involved run from 1 to 5000 (value of n)
 A loop will have to produce in increasing order numbers from 1 to 50000 to get the sum from left to
right
 A second loop will have to produce numbers in decreasing order from 50000 to 1

sum = 0
for n in range(1, 50001):
sum += 1/n;

print("Sum from left to right is", sum)

print()

sum = 0
for n in range(50000, 0, -1):
sum += 1/n

print('Sum from right to left is', sum)

Output

2. Suppose you save $100 each month into a savings account with the annual interest rate 5%. So, the
monthly interest rate is 0.005/12 = 0.00417. After the first month, the value in the account becomes
100 * (1 + 0.00417) = 100.42

After the second month, the value in the account becomes


(100 + 100.417) * (1 + 0.00417) = 201.25

After the third month, the value in the account becomes


(100 + 201.252) * (1 + 0.00417) = 302.51
and so on.

COURSE INSTRUCTOR: T. MIEBI


Write a program that prompts the user to enter an amount (e.g., 100), the annual interest rate (e.g.,
5), and the number of months (e.g., 6), and displays the amount in the savings account after each
month to the last month.
Solution
deposit = float(input('Enter amount deposited per month: '))
annualR = float(input('Enter annual rate: '))
months = int(input('Enter the duration in number of months: '))
balance = 0

# Calculate monthly rate


monthlyR = annualR / (12 * 100)

# Number of iterations = months.


# Which means number of values from range must match number of months.
# Values from 0 to (months - 1) = Number of iterations
for i in range(months):
print() # To space balance for each month
interest = (balance + deposit) * monthlyR
balance += (deposit + interest)
print('After', i + 1, 'month, balance =', round(balance, 2))
print()

Output (Sample)

3. Write a program that reads a set of positive numbers and displays: the sum, number, minimum, maximum,
and average of all the values entered. The program should stop reading numbers when a negative number
(SENTINEL VALUE) is entered.
A message stating that no value was entered should be displayed, if the sentinel value was the first
value entered.
Note: The sentinel value is a value that value, which is used communicate an intention (in the case
above, the intention to stop entering values).
Solution
# Initialize count, sum, minimum value, & maximum values to 0
count, sum, min, max = 0, 0, 0, 0

# Prompt for and read a value (first)


print('Enter integer (negative integer to end entry)')
value = int(input())

# Check for sentinel value to know whether to compute and repeat request
while value >= 0:
# Take count
count += 1

# Update sum
sum += value

COURSE INSTRUCTOR: T. MIEBI


# Update mininum if necessary
if value < min:
min = value

# Update maximum if necessary


if value > max:
max = value

# Read next value


value = int(input())

# Separate input tasks from output


print()

# Check if at least a value was entered


if count == 0:
print('No value was entered.')
else:
# Calculate average
avg = sum / count

# Display outputs
print('Sum of values is', sum)
print('No. of vlaues is', count)
print('Maximum value is', max)
print('Minumum value is', min)
print('Average value is', avg)

Output (Sample runs)

4. Write a program to display all the hour and minute values in a 24-hour clock, i.e.
0:00
0:01
:
01:00
01:01
:
23:59
Solution
# The outer loop is to control the hour (0 - 23)
# The inner loop is to control the minutes (0 - 59)

for h in range(24):
for m in range(0, 60, 15):

COURSE INSTRUCTOR: T. MIEBI


if m < 10:
# Single digit minutes should have a leading 0
min = '0' + str(m)
else:
min = m
print('%2d:%s' % (h, min))

Output (Sections)

5. Display all the prime numbers between 2 and 50, inclusively.


Solution
# Get all numbers from 2 to 50
for n in range(2, 51):
f = 2; # First factor to bring in is 2
while f < n: # Get all possible factors from 2 to (n - 1)
if n % f == 0: # If n is divisible by even one value of f
break # then n is not prime. Terminate loop
f += 1 # Get next factor, if previous one wasn't a factor

if f == n: # If no value of f from 2 to (n - 1) divided n


print(n, end = " ") # then print n because it is a prime number

Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

PRACTICE EXERCISES (SET 4)


1. You can use the [Link](seconds) function in the time module to let the program pause for the
specified seconds. Write a program that prompts the user to enter the number of seconds, displays a
message at every second, and terminates when the time expires. Here is a sample run:

2. Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume
that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the
largest number is 5 and the occurrence count for 5 is 4. (Hint: Maintain two variables, max and count.
The variable max stores the current maximum number, and count stores its occurrences. Initially,
assign the first number to max and 1 to count. Compare each subsequent number with max. If the number
is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment
count by 1.)

COURSE INSTRUCTOR: T. MIEBI


3. In business applications, you are often asked to compute the mean and standard deviation of data. The
mean is simply the average of the numbers. The standard deviation is a statistic that tells you how
tightly all the various data are clustered around the mean in a set of data. For example, what is the
average age of the students in a class? How close are the ages? If all the students are the same age,
the deviation is 0. Write a program that prompts the user to enter ten numbers, and displays the mean
and standard deviations of these numbers using the following formula:

Here is a sample run:

4. Write a program that displays all the prime numbers from 1 to 1000. The program should give a
formatted output which has 12 prime numbers per line, and each prime number is to occupy a field with
of 6 characters. The expected output is given below:

5. Write a program that displays the multiplication table shown below:

COURSE INSTRUCTOR: T. MIEBI


STRINGS
A string is a collection of 0 or more characters. All characters have a numeric code which helps in
providing the ones with symbols missing from keyboards, including characters and symbols from diverse
languages in the world. A single character therefore can be represented using
1. ‘symbol’ e.g. ‘a’, ‘5’, ‘%’ etc. Single quote as already known can be replaced with double or triple
quotes
2. ‘\uAAAA’ where AAAA is the a 4-digit hexadecimal number representing the code of the character. For
example, '\u6b22' = 欢, '\u8FCE' = 迎. Values used as code are from 0000 to FFFF.
3. ‘\ooo’ where ooo is the 3-digit octal code of the character. For example, ‘\066’ = ‘6’
4. ‘\xhh’ where hh is a 2-digit hexadecimal code of the character. For example, ‘\x40’ = ‘@’
5. chr(code) where character code in base 10. For example chr(36814) = 迎.
Note: The decimal code of a character (symbol preferably) provided as argument, can be returned using
the function ord(character). For example ord(‘迎’) = 36814, ord(‘6’) = 54, ord(‘\xAB’) = 171

ACCESS TO SINGLE CHARACTER


The characters that constitute a string have positions in it. These positions are called INDEXES and are
represented by integers (positive in one direction and negative in the other).
In left to right assignment, the leftmost character is given 0. The index of each character afterwards is
obtained by adding 1 to the index of the previous character (character to the left).
In right to left assignment, the rightmost character is given -1. The index of each character afterwards, is
obtained by subtracting 1 from that of the previous (character to the right).

String characters: P Y T H O N
Index (left to right): 0 1 2 3 4 5
Index (right to left): -6 -5 -4 -3 -2 -1

Reference to a single character => variable[index]. The variable can also be replaced by a value.
Examples
1. Given that code = ‘FCE 246’
code[0] = ‘F’
code[-1] = ‘6’

2. ‘Hello’[1] = ‘e’
Strings are said to be immutable because access to characters doesn’t provide the opportunity to change them.
This means code[6] = 4 will not work.

SLICING STRINGS
str[a : b]: returns a slice of the string made up of characters from index a, to index b – 1 (character at
index b is not included. For example ‘Bello’[0 : 4] = ‘Bell’. Points to note include:
 missing a => first character of the slice is at index 0 e.g. ‘Bello’[: 4] = ‘Bell’
 missing b => characters making the slice are from index a, to the end of the string e.g.
‘chant’[2 : ] = ‘ant’

COURSE INSTRUCTOR: T. MIEBI


It is important to remember that index values of characters are positive or negative, which means they can
be used interchangeably. That is ‘Bello’[-5 : 4] = ‘Bello’[-5 : -1] = ‘Bello’[0 : -1] = ‘Bello’[0 : 4] =
‘Bell’

str[a : b : n] also returns a slice of the preceding string, with a, and b same as above, but the characters
are picked in such a way that, every nth character after the current one makes it into the slice. If n is
positive the pick is from left to right, while if it is negative, it is from right to left. It is also
important to place the value of a, and b appropriately otherwise an empty string will be returned.
‘DO THE RIGHT THING’[0 : 17 : 8] = ‘DIN’
‘DO THE RIGHT THING’[ : : 8] = ‘DIN’
‘DO THE RIGHT THING’[17 : 0 : -7] = ‘GHT’

TRAVERSING A STRING
This refers to going through a string with the intention of accessing its characters, one after the other.
This is done through loops, especially the for-loop. The while loop uses the mathematical relationship
between the index values.
for var in string
process var which contains the current character
A character is copied per iteration into var, which then gets processed in the body. To illustrate this, the
program below prints a string vertically.
for ch in 'Hello':
print(ch)

Output

With the while-loop, the program is as shown below:


i = 0
while i < 5:
print('Hello'[i])
i += 1

Note: The highest index is 4 (number of characters - 1)

STRING LENGTH
len(string) returns the number of characters in the string. The argument is either a variable or value. For
example, len(‘Hello’) = 5, len(‘26\\11\\2018’) = 10

STRING METHODS
A function that is used through a variable or value with the aid of the dot operator(.) is called a METHOD.
There are several useful methods associated with strings in Python, some of which will examined below:

1. [Link]() returns a version of s where the first character of s is uppercase, while the rest are
lowercase.
‘HELLO EVERYONE’.capitalize() = ‘Hello everyone’
‘4n to code’.capitalize() = ‘4n to code’

2. [Link](fieldWidth, char) returns a copy of s centered within the specified fieldWidth and padded to
the left and right with space of char if it is provided.
‘GREAT’.center(12) = ' GREAT '
‘GREAT’.center(12, ‘*’) = '***GREAT****'

3. [Link](t, start, end) returns the number of occurrences of t in s or the slice of s obtained from
s[start : end]
'banana'.count('na') = 2
'banana'.count('an', 2) = 1
'banana'.count('na', 2, 6) = 2
COURSE INSTRUCTOR: T. MIEBI
'banana'.count('na', 2, 5) = 1
'banana'.count('an', 4) = 0

4. [Link](t, start, end) returns True if s or the slice of s from s[start : end] ends with t if t is a
single string or one of the strings in t if t is a TUPLE (Comma separated list of strings in brackets -
Details coming soon).
'banana'.endswith('na') = True
'banana'.endswith('na', 0, 4) = True
'banana'.endswith('an', 5) = False
'banana'.endswith(('na','ut')) = True
'coconut'.endswith(('na','ut')) = True
'banana'.endswith(('na','ut'), 0, 3) = False

5. [Link](size) returns a copy of x in which contained tabs have been replaced by spaces in
multiples of 8 or the size specified.
len(‘\t’) = 1
len(‘\t’.expandtabs()) = 8
len(‘\t’.expandtabs(4)) = 4

6. [Link](t, start, end) returns the leftmost position of t in s or the slice of s, s[start : end]. -1 is
returned if t is not found.
'coconut'.find('c') = 0
'coconut'.find('z') = -1
'coconut'.find('c', 1) = 2

[Link](t, start, end) is similar to [Link](), but returns the rightmost position.
'coconut'.rfind('o') = 3
'coconut'.rfind('o', 0, 3) = 1
'coconut'.rfind('u', 0, 3) = -1`

7. [Link](t, start, end) returns the leftmost position of t in s, or the slice of s, s[start : end]. An
error is generated if t is not found.
'coconut'.index('o') = 1
'coconut'.index('z') = ValueError: substring not found

[Link](t, start, end) is similar to [Link](), but returns the rightmost position.
'coconut'.rindex('o') = 3

8. [Link]() returns True if s is not empty, and all characters in it are alphanumeric (alphabets or
numbers).
'123'.isalnum() = True
'ab12'.isalnum() = True
'#4nky'.isalnum() = False

9. [Link]() returns True if s is not empty, and all characters in it are alphabets.
'abc'.isalpha() = True
'ab12'.isalpha() = False

10. [Link]() returns True if s is not empty, and every character in it is a digit.
'123'.isdigit() = True
'12ab'.isdigit() = False

11. [Link]() returns True if s is not empty, and it is a valid identifier.


'_4nky'.isidentifier() = True
'2go'.isidentifier() = False

COURSE INSTRUCTOR: T. MIEBI


12. [Link]() returns True if s has at least one lowercase character, and all its characters that can be
in lowercase are in lowercase.
'1234'.islower() = False
'3Nt'.islower() = False
'abc'.islower() = True

13. [Link]() returns True if s is nonempty and every character in s is a whitespace character.
'\t\n'.isspace() = True
'a\tb'.isspace() = False

14. [Link]() returns True if s is nonempty and is in title case (first letter of each word is uppercase
while the rest are lowercase).
'Hello everyone'.istitle() = False
'Hello Everyone'.istitle() = True

15. [Link]() returns True if s has at least one uppercase character and all its characters that can be
in uppercase are in uppercase.
'123'.isupper() = ‘False’
'12H'.isupper() = ‘True’

16. [Link](sequence) returns a string in which s is planted between every item (character) in the sequence.
'*'.join('HELLO') = 'H*E*L*L*O'

17. [Link](width, char) return a copy of s in which s is aligned to the left of the field width provided
and the excess space may be padded with char (if provided).
'Hi'.ljust(10) = 'Hi '
'Hi'.ljust(10, '*') = 'Hi********'

[Link](width, char) return a copy of s in which s is aligned to the right of the field width provided
and the excess space may be padded with char (if provided).
'Hi'.rjust(10) = ' Hi'
'Hi'.rjust(10, '*') = '********Hi'

18. [Link](t) returns a tuple of three strings – the portion of s before the leftmost occurrence of t
in s, t, and portion of s after the leftmost occurrence of t in s.
'coconut'.partition('o') = ('c', 'o', 'conut')

[Link](t) returns a tuple of three strings – the portion of s before the rightmost occurrence of
t is s, t, and the portion of s after the rightmost occurrence of t in s.
'coconut'.rpartition('o') = ('coc', 'o', 'nut')

19. [Link](old, new, n) returns a copy of s in which every or n (if provided) occurrence of old, in s
have been replaced by new. A string identical to s is returned if old is not found.
'wow'.replace('w', 'l') = 'lol'
'wow'.replace('w', 'l', 1) = 'low'

20. [Link]() => returns a lowercase version of the preceding string.


‘Hello’.lower() = ‘hello’

21. [Link](t, n) returns a list of strings from splitting s using t (or space if t isn’t provided) as
delimiter. Splitting is done at most n times, if n is provided.
'Hello everyone'.split() = ['Hello', 'everyone']
'banana'.split('a') = ['b', 'n', 'n', '']
'banana'.split('a', 2) = ['b', 'n', 'na']

[Link](t, n) is similar to [Link](), but splits from right to left (effective with n that is less
than the maximum split possible)
COURSE INSTRUCTOR: T. MIEBI
'banana'.rsplit('a', 2) = ['ban', 'n', '']

22. [Link](f) returns lines of string from splitting s using line terminators (\n). The line
terminator are only a part of the returned strings if f is True.
'''Hi everyone
welcome to our
meeting today'''.splitlines() = ['Hi everyone', 'welcome to our', 'meeting today']
'Hi everyone!!!\nHow are we\ntoday.'.splitlines() = ['Hi everyone!!!', 'How are we', 'today.']
'We are\nhaving a\ngreat time'.splitlines(False) = ['We are', 'having a', 'great time']
'We are\nhaving a\ngreat time'.splitlines(True) = ['We are\n', 'having a\n', 'great time']

23. [Link](t, start, end) returns True if s or the slice of s from s[start : end] starts with t if t
is a single string or one of the strings in t if t is a tuple.
'coconut'.startswith('co') = True
'coconut'.startswith('oc') = False
'coconut'.startswith('oc', 1) = True

24. [Link](ch) returns a version of s in which all leading (left of s) and trailing (right of s)
whitespace characters or ch (if provided) are removed.
' Hello '.strip() = 'Hello'
'\tHello\t\n'.strip() = ‘Hello’
' Hello****'.strip('*') = ' Hello'

[Link](ch) similar to [Link]() but only removes characters from the left.
' Hello '.lstrip() = 'Hello '
'***Hi***'.lstrip('*') = 'Hi***'

[Link](ch) similar to [Link](), but only removes characters from the right.
' Hello '.rstrip() = ' Hello'
'***Hi***'.rstrip('*') = '***Hi'

25. [Link]() => returns an uppercase version of the preceding string.


‘Hello’.upper() = ‘HELLO’

26. [Link]() returns a version of s in which uppercase characters are lowercase, while lowercase
characters are uppercase.
'hI'.swapcase() = 'Hi'

27. [Link]() returns a copy of s in which the first letter of each word is uppercase and other letters are
in lowercase.
'INTRODUCTION TO PYTHON'.title() = 'Introduction To Python'

28. [Link](w) returns a copy of s that is padded with leading zeros if s is shorter than w, otherwise it
returns an identical copy of s.
'2.4'.zfill(6) = '0002.4'
'2.4'.zfill(3) = '2.4'

USER-DEFINED FUNCTIONS
A function is a sequence of instructions with a name. a function is called for usage, by its name with the
supply of 0 or more values called arguments. Important facts to note include:
1. Function parts: head, and body
2. Function head: def (keyword), name, bracket opened, 0 or more parameters, bracket closed, colon (:)
def name(param, param, …, param): => for function with more than 1 parameter
def name(param): => for function with only 1 parameter
def name(): => for function with no (0) parameter
3. Function body: indented sequence of statements

COURSE INSTRUCTOR: T. MIEBI


Other important things to mention include:
1. Calling a function requires it name and values called arguments (required for functions with
paramenters) e.g. name(), name(arg), name(arg, arg, …, arg)
2. The definition of a function must be presented before the function is called up for execution.
3. The definition of a function is not executed because it is descriptive in nature (describes the
makeup of the function)
4. Calling function A in the definition of function B doesn’t equate to function A been executed. This
is because the call was made in a definition.
5. If a function is to return a value at the completion of its execution, the value or its reference
(name) is sent back using the keyword return i.e. return value, or return name.
6. For a function that returns value, returning the value marks the end of the function execution.
Statements under the return-statement (if any) are left unexecuted.

Example
The program below has two functions defined. One uses the diameter to return the area of a circle, while the
other uses the height and diameter to return the volume of a cone.
For this program, the solid of interest is a cone (solid with a circular base)

Code
import math

# FUNCTION THAT RETURNS AREA


def getArea(diameter):
return [Link] * d * d / 4

# FUNCTION TO RETURN VOLUME


def getVolume(diameter, height):
area = getArea(diameter)
return area * height / 3

# Prompt for the diameter and height


d, h = eval(input('Enter the diameter and height: '))

# Display volume
print('\nVolume of cone is', getVolume(d, h))

Output (Sample Run)

POSITIONAL & KEYWORD ARGUMENTS


The function below is to print a line made a specified character (type str) matching the length (type int)
specified.

def printLine(char, length):


for i in range(length):
print(char, end = '')
print()

Positional arguments are regular arguments presented to match function parameters in order and type. Using
the above function.
 printLine(‘*’, 45) is good because the arguments (positional) match the function parameters.
 printLine(45, ‘*’) will generate an error because the arguments do no match the function parameters.
Keyword arguments take the form parameter = argument, and they are used to provide specific arguments for
specific function parameters.

COURSE INSTRUCTOR: T. MIEBI


 print(char = ‘*’, length = 30) => ******************************
 print(length = 30, char = ‘#’) => ##############################
Order doesn’t matter when all arguments are keyword arguments hence the two calls above will work fine.
Note
print(len = 30, char = ‘*’) will not work because len is not listed as a parameter in the function.

It is also possible to mix both types of arguments. The rule is that positional argument(s) are followed by
keyword argument(s). Ordering is not important among the keyword arguments. The mix should be such that in
terms of position, keyword arguments from the right divide, while positional arguments to are to the left.
Sandwiching isn’t acceptable. The function below is used to illustrate all of these.

def printAvg(a, b, c, d):


print(a + b + c + d)

Below are some of the error-generating function calls based on the above function:
 printAvg(2, 3, 4, b = 5) # b the second parameter, is 4th argument
 printAvg(2, b = 3, 4, 5) # keyword argument sandwiched by positional arguments

Acceptable function calls include:


 printAvg(2, 3, 4, d = 5)
 printAvg(2, 3, c = 4, d = 5)
 printAvg(2, 3, d = 4, c = 5) # keyword arguments with order changed

VARIABLE SCOPE
The region in a program within which the existence of a variable, is recognized and can consequently be
accessed, is called its scope.
A variable defined in a function is called a local variable. Local variables cannot be accessed from outside
the function (they don’t exist outside the function). This means that, a variable with the same name as a
local variable can still be created outside the function. For example, variable a in the code segment below:

def printAvg(a, b, c, d):


print(a + b + c + d)

a = 45 # a in printAvg() has no existence outside it


print(a)

A variable that is not declared in any function is called a global variable because it can be accessed from
anywhere within the program. For example, variable rate in the code segment below:

rate = 0.13

def getInterest(amount):
return rate * amount

print('Interest rate is', rate)

DEFAULT ARGUMENTS
Default arguments are values assigned to parameters in a function definition. The implication of this is
that, it is not compulsory for arguments to be supplied for such parameters during function calls.
If arguments aren’t supplied in the function call, the default arguments are used by the function. All these
are illustrated in the program below:
def printVol(d = 1, h = 1):
from math import pi
vol = pi * d * d * h / 4
print('Diameter:%4f Height:%4f Volume: %f\n' % (d, h, vol))

printVol()
COURSE INSTRUCTOR: T. MIEBI
printVol(2, 2)
printVol(h = 2.5, d = 5)
printVol(h = 8)
printVol(d = 8)
printVol(6) # Single argument goes to first parameter, d

Output is presented below:

RETURNING MULTIPLE VALUES


This is done by simply providing all of these values as a comma-separated list after the return keyword.
Receiving the returned values requires assigning them to a comma-separated list of variables. All these are
demonstrated in the program below:

# Function to return total surface area & volume of cylinder


def getAreaVolume(r, h):
from math import pi
area = 2 * pi * r * (r + h)
vol = pi * r * r * h
return area, vol # Return area and volume

# Use function to get area & volume of cylinder with r = 3.5, & h = 5
area, volume = getAreaVolume(3.5, 5)
print('%6s: %f' % ('Area', area))
print('%6s: %f' % ('Volume', volume))

Output

MODULARISATION
A module is same as a program. For a function to be used, its definition/description must be accessible. It
can be provided in the module where it will be used or in another module within the same directory.
Accessing the definition of a function in a separate module is what requires using the import statement.
Below are different variants of the import statement, and the reference format for its content:
1. import module
2. import module1, module2, …, moduleN (import multiple modules)
3. import module as preferred_name
In each of the above cases, access to the content (data or function) is through the module or the
preferred_name

4. from module import content


5. from module import content as preferred_name
6. from module import content1, content2, …, contentN
7. from module import * (get all content of the module)

Example
1. Functions permute, and combine are both defined in the file [Link]
2. These functions are then used in the program that comes after.
[Link]
from math import factorial

COURSE INSTRUCTOR: T. MIEBI


def permute(n, r):
return factorial(n) / factorial(n - r)

def combine(n, r):


return permute(n, r) / factorial(r)

Program (To be interpreted)


from functions import *

n = 10
print('n =', n)

print('\n%3s%10s%8s' % ('r', 'nPr', 'nCr'))

for r in range(11):
print('%3d%10d%8d' % (r, permute(n, r), combine(n, r)))

Output

Sometimes, statements needed for the testing of the functions in a module might be included in the module.
These statements are only to be executed if the module containing these functions is interpreted, not when
it is imported into another module. The function above is represented below, to illustrate how this is done.
Example 1
from math import factorial

def permute(n, r):


return factorial(n) / factorial(n - r)

def combine(n, r):


return permute(n, r) / factorial(r)

# Execute statement under both here, and when module is imported


print('This is a statement in [Link]')

# Don't execute statements under if module is imported


if __name__ == '__main__':
print('\n%3s%10s%8s' % ('r', 'nPr', 'nCr'))
n = 3
for r in range(4):
print('%3d%10d%8d' % (r, permute(n, r), combine(n, r)))

Output
This is a statement in [Link]

r nPr nCr
0 1 1
COURSE INSTRUCTOR: T. MIEBI
1 3 3
2 6 3
3 6 1
Example 2
[Link]
from math import factorial

def permute(n, r):


return factorial(n) / factorial(n - r)

def combine(n, r):


return permute(n, r) / factorial(r)

# Execute statement under both here, and when module is imported


print('This is a statement in [Link]')

# Don't execute statements under if module is imported


if __name__ == '__main__':
print('\n%3s%10s%8s' % ('r', 'nPr', 'nCr'))
n = 3
for r in range(4):
print('%3d%10d%8d' % (r, permute(n, r), combine(n, r)))

[Link] (Application to be interpreted)


import functions

Output
This is a statement in [Link]

AN EMPTY FUNCTION (A STUB)


A function may not have a body (empty) because implementation details may not be available. If the function
is presented with only the head, it will raise an exception during interpretation. In order to prevent this,
the keyword pass can be presented as the body of the function. This is as shown below:

def emtyFxn():
pass

VARIABLE ARGUMENTS
A single parameter in a function definition is tied to a single argument. It is possible to make a single
parameter represent one or more arguments.
 Preceding a parameter with *, will make it represent one or more regular arguments. The arguments are
made available in the body in a tuple. Getting each argument value requires going through the tuple.
Code
def fxn(*a):
print(type(a))
print(a)

fxn(1,2,3,4,5,6)
Output
<class 'tuple'>
(1, 2, 3, 4, 5, 6)

 Preceding a parameter with **, will make it represent one or more key-value arguments which are made
available in a dictionary in the body during implementation. The keys in the argument must all be valid
identifiers.
Code
def fxn(**kwa):
print(type(kwa))

COURSE INSTRUCTOR: T. MIEBI


for key, value in [Link]():
print(key, value)

fxn(MTH105 = 56, PHY105 = 43, CHM101 = 89)


Output
<class 'dict'>
MTH105 56
PHY105 43
CHM101 89

WORKING WITH MODULES


One or more user-defined functions can be defined in one file (aka module) and used in another. The module
containing the functions, first has to be imported.
The two files can be in the same directory (easier) or different directory. When in different directories,
the directory containing the module to be imported must be a part of [Link] for this to work.
Example 1 (same directory)
[Link] is the module with the function to be used. Its code is given below:

def checkIfPrime(numberToCheck):
for x in range(2, numberToCheck):
if(numberToCheck%x == 0):
return False
return True

[Link] is the module that will use the function in [Link]

import prime
answer = [Link](19)
print(answer)

Result
True

Example 2 (different directory)


There just a little adjustment that has to be made to [Link] after [Link] is relocated to a different
director. [Link] will be as presented below:

import sys
if 'C:\\Users\\Tee\\Desktop\\MyModules' not in [Link]:
[Link]('C:\\Users\\Tee\\Desktop\\MyModules')

import prime
answer = [Link](19)
print(answer)

LISTS
This is a data type that allows the storage a sequence of distinct data of any number/size. It should be one
of the data type of choice when dealing with multiple data.

CREATING LISTS
Creating a list requires most importantly, supplying a name to which is assigned the created list is
assigned. The sequence of data in the list can be mixed.
The statements below create empty lists
lst = []
lst = list()

The statements below create lists initialize them with the values (mixed or not) provided.
COURSE INSTRUCTOR: T. MIEBI
lst = [1, 2, 3]
lst = list(range(0, 5)) # list initialized with 0, 1, 2, 3, 4
lst = list('abcd') # list initialized with characters a, b, c, and d
lst = ['UG/00/0263', 23, 'M', 'Sagbama', 200] # initialized with mixed data

OPERATIONS WITH LISTS


1. x in lst: returns True if x is in the sequence.
'red'in ['green', 'blue', 'red'] = True
'pink' in ['green', 'blue', 'red'] = False

2. x not in lst: returns True if x is not in the sequence.


'red'in ['green', 'blue', 'red'] = False
‘pink' in ['green', 'blue', 'red'] = True

3. lst1 + lst2: returns a concatenation of the Two sequences.


lst1 = list('abcd')
lst2 = list('1234')
lst1 + lst2 = ['a', 'b', 'c', 'd', '1', '2', '3', '4']

4. lst * n, n * lst: returns a n copies of the sequence concatenated.


lst = [1, 2, 3]
let * 3 = [1, 2, 3, 1, 2, 3, 1, 2, 3]

5. lst[n] returns the element of the sequence @ index n.


lst = ['green', 'red’, ‘white']
lst[0] = 'green'
lst[-1] = 'white'

6. lst[a : b] returns a slice of the sequence made of elements from index a to b - 1 (element before b, to
be precise).
lst = ['red', 'blue', 'green', 'pink']
lst[0 : 3] = ['red', 'blue', 'green']
7. len(lst) returns the length of the sequence (# of elements contained).
lst = [-1, 1, 2, 3, 5]
len(lst) = 5

8. max(lst) returns the largest element in the sequence of elements (of the same type, no mixing) that can
be ordered.
lst[4, 6, 7]
max[lst] = 7

9. min(lst) returns the smallest element in the sequence of elements (of the same type) that can be
ordered.
list[6, 2, 3]
min(lst) = 2

10. sum(lst) returns the sum of all the elements in the sequence. All elements in the sequence must be
numeric for this to work.
lst[2, 4, 7]
sum(lst) = 13

Comparing two list is done with the usual suspects: ==, !=, <, <=, >, >=. The result is based on comparing
corresponding elements from both sequences, one after the other.
The comparison for strings is based on dictionary order of corresponding characters in corresponding strings
been compared. The result is determined by the fact that, later characters in the Unicode chart are greater
than earlier characters in the chart in terms of their codes. This can easily be verified by using ord() to
get the codes of the characters been compared. The ordering for alphanumeric characters is as given below:

COURSE INSTRUCTOR: T. MIEBI


0 - 9 (48 - 57)
A - Z (65 - 90)
a - z (97 - 122)

A result is returned from the very first compared pair that creates a difference (depending on the
comparison) between the sequences.
['a', 'B'] > ['a', 'b'] = False # from B and b
['green', 'red', 'blue'] < ['red', 'blue', 'green'] = True # from g in green and r in red

TRAVERSING A LIST
Traversing a list requires using a for-loop preferably.
for e in list:
do something with e
Example
lst = list('abcdefghijkl')
i = 0
for c in lst:
print(' ' * i, end = '')
print(c)
i += 1

Output
a
b
c
d
e
f
g
h
i
j
k
l

Using index values, it is also possible to do the same with elements at odd indexes.
lst = list('abcdefghijkl')
for i in range(1, len(lst), 2):
print(' ' * i, end = '')
print(lst[i])

An element is copied into e, in each iteration, and gets processed in the body of the loop. The above
program in a while-loop is as given below:

lst = list('abcdefghijkl')
i = 1
while i < len(lst):
print(' ' * i, end = '')
print(lst[i])
i += 2

Output (from both programs)


b
d
f
h
j
COURSE INSTRUCTOR: T. MIEBI
l

METHODS ASSOCIATED WITH LISTS


Presented below are so of the methods associated with lists:
3. [Link](x) will append x to the list. This will make x the next element in lst consequently
increasing its length/size. x can be any of the data type already treated. It can even be a sequence
data type.
lst = [2, 3, 4]
[Link]('hello') = [2, 3, 4, 'hello']

4. [Link](x) returns the number of times x occurs in lst.


['green', 'white', 'green'].count('green') = 2

5. [Link](l) appends all the members of l (a collection) to lst. This has the same result as lst += l.
['green', 'white', 'green'].extend('hi') = ['green', 'white', 'green', 'h', 'i']

6. [Link](x, a, b) returns the index of the leftmost occurrence of x in the list or slice of the list
from a:b.
['C', 'a', 'n', 'a', 'd', 'a'].index('a') = 1
['C', 'a', 'n', 'a', 'd', 'a'].index('a', 2, 5) = 3

7. [Link](index, x) will inaert x into lst at the specified index, displacing the original occupant to
the right. Specify an index greater than or equal to the length of lst, appends x to it.
['s', 't', 'e', 'm'].insert(3, 'a') = ['s', 't', 'e', 'a', 'm']
['s', 't', 'e', 'a', 'm'].insert(7, 'y') = ['s', 't', 'e', 'a', 'm', 'y']

8. [Link]() returns and removes the rightmost element from lst consequently reducing its length by 1.
lst = ['m', 'a', 't', 'e']
[Link]() = 'e'
lst = ['m', 'a', 't'] # lst after executing pop()

9. [Link](index) returns and removes the element at the specified index.


lst = ['m', 'a', 't', 'e']
[Link](0) = 'm'
lst = ['a', 't', 'e'] # lst after executing pop()

8. [Link](x) removes the leftmost occurrence of x in lst or generates an error (valueError) if x is


not found in lst.
lst = ['a', 'd', 'a', 'm'] # lst before remove() got executed
[Link]('a')
lst = ['d', 'a', 'm'] # lst after remove() got executed

9. [Link]() reverses lst.


lst = ['t', 'e', 'e', 'm'] # before reversal
[Link]()
lst = ['m', 'e', 'e', 't'] # after reversal

10. [Link]() sorts lst in ascending order, that is moving from left to right, elements will be
increasing in value.
lst = [10, 2, 13, -1, 10, 2, 5] # before sorting
[Link]()
lst = [-1, 2, 2, 5, 10, 10, 13] # after sorting

COPYING LISTS
Assigning one list to another list (names) doesn’t equate to having two versions of the list in memory. It
only means that the single list has two names through which it can be accessed/processed.
COURSE INSTRUCTOR: T. MIEBI
The program below illustrates this:

print('BEFORE ASSIGNMENT')
lst1 = list('1234')
print('lst1 =', lst1)

lst2 = []
print('lst2 =', lst2)

# Assign lst1 to lst2


lst2 = lst1

print('\nAFTER ASSIGNMENT')
print('lst1 =', lst1)
print('lst2 =', lst2)

# TEST FOR IDENTITY


print('\nIDENTITY TEST')
print('lst1 is lst2 =', lst1 is lst2)

# PROCESS LIST THROUGH lst1


[Link]('5')

# DISPLAY BOTH LISTS


print("\nAFTER APPENDING '5' TO lst1")
print('lst1 =', lst1)
print('lst2 =', lst2)

OUTPUT
BEFORE ASSIGNMENT
lst1 = ['1', '2', '3', '4']
lst2 = []

AFTER ASSIGNMENT
lst1 = ['1', '2', '3', '4']
lst2 = ['1', '2', '3', '4']

IDENTITY TEST
lst1 is lst2 = True

AFTER APPENDING '5' TO lst1


lst1 = ['1', '2', '3', '4', '5']
lst2 = ['1', '2', '3', '4', '5']

If the intention is to create a duplicate version in memory, then it is necessary to add to the empty lst2
each element in lst1. The above program will now be modified by replacing the assignment operation with
extension (extend the empty lst2 with lst1). That is
lst1 = lst2
should be replaced by
[Link](lst1)

The output from this change is given below:

BEFORE ASSIGNMENT
lst1 = ['1', '2', '3', '4']
lst2 = []

AFTER ASSIGNMENT
COURSE INSTRUCTOR: T. MIEBI
lst1 = ['1', '2', '3', '4']
lst2 = ['1', '2', '3', '4']

IDENTITY TEST
lst1 is lst2 = False

AFTER APPENDING '5' TO lst1


lst1 = ['1', '2', '3', '4', '5']
lst2 = ['1', '2', '3', '4']

MULTIDIMENSIONAL LISTS
This is a list in which members are lists i.e. list of lists.
lst = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] creates a list best pictured in the form of the table
shown below:
1 2 3 4
5 6 7 8
9 10 11 12
Access to a member requires two index values along with the name of the list. The first index value picks
the row, while the second represent the column in the picked row. For example lst[0][2] represents the
element from row 1, and column 3 which is 3.

 len(lst) = number of rows


 len(lst[index]) = number of columns in the row

Traversing a multidimensional list requires nested loops. For example, the above list will require two
nested loops. The code below prints the values in the list one after the order, maintaining their position.

Code
lst = [[1, 2, 3, 4], [5, 6, 7, 8]]

for i in range(len(lst)):
for j in range(len(lst[i])):
print('%4d' % lst[i][j], end = '')
print('\n')

Output
1 2 3 4

5 6 7 8

It has to be mentioned that nesting lists can go even deeper i.e. beyond two dimensions. The number of loops
needed traversing the list depends on the degree of nesting.

TUPLE
A tuple is a data type that represents collection of 0 or more comma-separated list of same or different
elements (enclosed in parentheses) that cannot be altered after creation. By implication, its length cannot
be changed, elements can’t be sorted, or deleted. It is the fixed/constant variant of a list.

CREATING TUPLES
1. tup = () # creates an empty tuple
2. tup = (1, 2, 3) # a list of 3 elements
3. tup = tuple([4, 6, 7, 9]) # converts the list to the tuple (4, 6, 7, 9)
4. tup = tuple(‘abcd’) # converts the string to the tuple (‘a’, ‘b’, ‘c’, ‘d’)
5. tup = tuple(range(4)) # creates a tuple from the values returned by range() i.e. (0 , 1, 2, 3)

COURSE INSTRUCTOR: T. MIEBI


PROCESSING TUPLES
Most of the operations performed with lists can also be performed with tuples. Some of these are illustrated
with the examples below:
1. 4 in (1, 3, 5, 8) = False
2. 4 not in (1, 3, 5, 8) = True
3. (1, 2) * 2 = 2 * (1, 2) = (1, 2, 1, 2)
4. (2, 4, 6, 10)[1] = 4
5. (1, 2, 3, 4, 5)[1 : 4] = (2, 3, 4)
6. len((1, 2, 3, 6)) = 4
7. max((1, 2, 3, 4, 9)) = 9
8. min((1, 2, 3, 4, 9)) = 1
9. sum((3, 4, 3, 4)) = 14

The members of a tuple can also be other collection types e.g. strings, lists, tuples etc.
1. (3, ['a', 'b'], 'c')
2. ((3, 4), 4, "Hello", ['hi', 2.3])

SET
It is a collection of 0 or more unique unordered data (enclosed in braces). The term “unique” stems from the
fact that duplicates aren’t allowed in a set.

CREATING A SET
1. s = set() # creates an empty set i.e. {}
2. s = {1, 2, 3} # creates a set with the elements provided
3. s = set([1, 3, 4]) # creates the set {1, 3, 4} from the list
4. s = set(‘abc’) # creates the set {‘b’, ‘a’, ‘c’} from the string
5. s = set((2, 2, 4)) # creates the set {2, 4} out from the tuple, with duplicates eliminated

In each of the above cases with values provided, duplicate values are collapsed to one in order to maintain
the uniqueness of values in the set.

PROCESSING SETS
1. [Link](v) adds to the set s.
s = {2, 3, 4}
[Link](‘hi’)
print(s) # s = {2, 3, 4, ‘hi’}

2. [Link](v)/[Link](v) removes v from s. Throws KeyError exception when v is not found


s = {2, 3, 4}
[Link](3)
print(s) # s = {2, 4}

3. [Link](t) / s <= t: returns True if s is a subset of t (s only contains all or some of the elements
in t).
{1, 2, 3}.issubset({1, 2, 3}) = True
{1, 2, 3}.issubset({1, 2, 3, 4}) = True
{1, 2, 3, 4}.issubset({1, 2, 3}) = False
{1, 2, 3} <= {1, 2, 3, 4} = True
{1, 2, 3, 4} <= {1, 2, 3} = False

4. s < t returns True if s is a proper subset of t (s only contains some of the elements in t).
{1, 2, 3} < {1, 2, 3} = False
{1, 2, 3} < {1, 2, 3, 4} = True
{1, 2, 3, 4} < {1, 2, 3} = False

5. [Link](t) / s >= t: returns True if s is a superset of t (s contains all elements in t and maybe
more)

COURSE INSTRUCTOR: T. MIEBI


{1, 2, 3, 4}.issuperset({1, 2, 3, 4}) = True
{1, 2, 3, 4}.issuperset({2, 3, 4}) = True
{1, 2, 3, 4}.issuperset({3, 4, 6}) = False

6. s > t returns True if s is a proper superset of t i.e. s contains all the elements in t and more.
{1, 2, 3, 4} > {1, 2, 3, 4} = False
{1, 2, 3, 4} > {1, 2, 3} = True

7. [Link](t) / s | t: produces a set which is a union of s and t (unique collection of elements in s & t,
common and uncommon)
{1, 2, 3}.union({2, 3, 4, 5}) = {1, 2, 3, 4, 5}

8. [Link](t) / s & t: produces a set which contains elements common to s and t


{1, 2, 3}.intersection({2, 3, 4, 5}) = {2, 3}

9. [Link](t) / s – t: returns a set with elements of s missing in t


{1, 2, 3, 4}.difference({3, 4, 5}) = {1, 2}

10. [Link]() removes all the elements in s


{1, 3, 4, 6}.clear() = set() = {}

11. [Link]() returns a copy of s


{1, 3}.copy() = {1, 3}

12. s.difference_update(t) / s -= t: removes all elements of s from t i.e. it saves s – t in s.


>>> s = {1, 2, 3, 4}; t = {4, 5, 6}
>>> print(s)
{1, 2, 3, 4}
>>> s.difference_update(t)
>>> print(s)
{1, 2, 3}

13. s.intersection_update(t) / s &= t: replaces all elements in s with the common elements of s and t
>>> s = {1, 2, 3, 4}; t = {4, 5, 6}
>>> print(s)
{1, 2, 3, 4}
>>> s.intersection_update(t)
>>> print(s)
{4}

14. [Link](t) returns True if s and t have no common element.


>>> {1, 2, 3}.isdisjoint({1, 5, 6})
False
>>> {1, 2, 3}.isdisjoint({5, 6, 7})
True

15. [Link]() returns and removes a random element from s. It returns KeyError if unsuccessful.
>>> s = {1, 3, 5, 7}
>>> [Link]()
1
>>> s
{3, 5, 7}

16. s.symmetric_difference(t) / s ^ t: returns a set of all uncommon elements between s and t (all elements
excluding the common ones).
>>> {1, 2, 3, 4}.symmetric_difference({3, 4, 5, 6})
{1, 2, 5, 6}

COURSE INSTRUCTOR: T. MIEBI


17. s.symmetric_difference_update / s ^= t: saves all the uncommon elements between s and t in s.
>>> s = {1, 2, 3, 4, 5}
>>> t = {3, 4, 5, 6, 7}
>>> print(s)
{1, 2, 3, 4, 5}
>>> s ^= t
>>> print(s)
{1, 2, 6, 7}

18. [Link](t) / s |= t: adds all items of t missing in s, to s (save the union of s and t in s).
>>> s = {1, 2, 3}
>>> t = {3, 4, 5}
>>> print(s)
{1, 2, 3}
>>> s |= t
>>> print(s)
{1, 2, 3, 4, 5}

Other important functions and operators associated with set include:

1. len(s) returns the numbers of elements in s


2. max(s) returns the largest element in s
3. min(s) returns the smallest element in s
4. sum(s) returns the sum of the elements in s
5. == and != are both used to test the equality of sets
6. in and not in are both used to check the membership of elements with respect to a given set.

The concept of slices and index values don’t apply to sets because they are not ordered.
A set can only contain immutable data types, which are said to be HASHABLE i.e. hash(data) will produce an
integer instead of an exception/error. Examples of immutable types are int, float, bool string, and tuple;
while some of the mutable types are lists and sets. With this
 s = {2, 4, ‘hi’, (7, 8)} => good (tuple is immutable)
 s = {2, 4, ‘hi’, [7, 8]} => bad (list is mutable)
 s = {2, 4, ‘hi’, {7, 8}} => bad (set us mutable hence the concept of a set of sets is dead on
arrival)

Of importance is the fact all “update” methods of set can take any collection data type as argument, but
their operator equivalents require both operands to be sets. This implies that if s = {1, 2, 3}, then
 [Link](‘hi’) => good
 [Link]([3, 4]) => good
 s |= ‘hello’ => bad

DICTIONARY/MAP
This is a mutable collection of 0 or more elements comprised of a pair of data, the first of which is called
the KEY, and the second the VALUE. i.e. contained elements in a dictionary ae in key-value pairs. Facts
worthy of note include:
1. Dictionaries are marked with braces like sets.
2. Keys must be unique and immutable.
3. Values can be immutable and duplicated
4. Getting a value from a dictionary requires supplying its key as index.

CREATING DICTIONARIES
1. {} # creates an empty dictionary
2. dict() = {} # creates an empty dictionary
3. {1:False, 2:True}
4. dict([(1, True), (2, False)]) = {1: True, 2: False} # creates a dictionary from a list of tuples

COURSE INSTRUCTOR: T. MIEBI


5. dict(code = 'FCE246', Tutor = 'Tee') = {'code': 'FCE246', 'Tutor': 'Tee'} # creates a dictionary from
the keyword (valid identifiers) arguments presented by converting each keyword to a string.

Access to a value after creating a dictionary requires name/reference as well as the key tied to the value.
>>> d = {1: True, 2: False, 3: True}
>>> d[1]
True

DICTIONARY METHODS
1. [Link]() removes all elements from d
>>> d = {1: True, 2: False}
>>> d
{1: True, 2: False}
>>> [Link]()
>>> d
{}

2. [Link]() returns a copy of d (duplicate)


>>> d = {1: True, 2: False}
>>> f = [Link]()
>>> f
{1: True, 2: False}
>>> f is d
False

3. [Link](key) returns the value associated with key in d, or None (no value) if key isn’t in d.
>>> [Link](1)
True

4. [Link](key, v) returns the value associated with key in d, or v if key is not in d.


>>> [Link](2, 'Missing')
False
>>> [Link](7, 'Missing')
'Missing'

5. [Link]() returns a VIEW (read-only sequence data) of all key-value pairings in d


>>> [Link]()
dict_items([(1, True), (2, False)])

6. [Link]() returns a view of all keys in d


>>> [Link]()
dict_keys([1, 2])
7. [Link](k) returns the values associated with the key k, and removes the element afterwards. It raises
KeyError if k is not in d.
>>> [Link](2)
False
>>> d
{1: True}

8. [Link](k, v) returns the value associated with k, and removes it, or returns v if k is not in d
>>>>[Link](4, 'Missing')
'Missing'

9. [Link]() returns and removes an arbitrary key-value pair from d, or raises KeyError exception if d
is empty
>>> [Link]()
(1, True)

COURSE INSTRUCTOR: T. MIEBI


10. [Link](k, v) returns the value associated with k. If k is not in d, a new value with k as key and
v or None (if v is not provided) is added to d.
>>> [Link](1, True)
False
>>> [Link](3, True)
True
>>> d
{1: False, 3: True}

11. [Link](z) adds to d all key-value pairs of z, not in d, and for all keys in d and z, it replaces the
key-value pair in d with that of z.
>>> d = {1: True, 2: False}
>>> z = {1: False, 3: True}
>>> [Link](z)
>>> d
{1: False, 2: False, 3: True}

TRAVERSING DICTIONARIES
Traversing a dictionary to access multiple elements within it requires the use of loops most especially, the
for-loop. The examples below show the different ways in which this can be done:
Example 1
>>> grdPts = dict(A=5,B=4,C=3,D=2,F=0)
>>> for key in grdPts:
>>> print(key)

A
B
C
D
F

Example 2
>>> grdPts = dict(A=5,B=4,C=3,D=2,F=0)
>>> for key in grdPts:
>>> print(key, '=', [Link](key))

A = 5
B = 4
C = 3
D = 2
F = 0

Example 3
>>> grdPts = dict(A=5,B=4,C=3,D=2,F=0)
>>> for key in grdPts:
>>> print('%s = %d' % (key, grdPts[key]))

A = 5
B = 4
C = 3
D = 2
F = 0

Example 4
>>> grdPts = dict(A=5,B=4,C=3,D=2,F=0)
>>> for key, value in [Link]():

COURSE INSTRUCTOR: T. MIEBI


>>> print(key, '=', value)

A = 5
B = 4
C = 3
D = 2
F = 0

Example 5
>>> grdPts = dict(A=5,B=4,C=3,D=2,F=0)
>>> for item in [Link]():
>>> print(item[0], '=', item[1])

A = 5
B = 4
C = 3
D = 2
F = 0

EXCEPTION HANDLING
Exceptions or errors come in various forms and the names below represent some of them:
1. Exception: general name for all types of exceptions
2. AttributeError: from failure in initialization due to references or assignment
3. IOError: failure in input/output operations
4. ImportError: missing module definition, or missing reference in module specified.
5. IndexError: index/subscript is out of range
6. KeyError: missing key
7. KeyboardInterrupt: raised when Ctrl + C or Del is pressed
8. NameError: raised when a local or global name is missing
9. TypeError: raised when an operator or function is use with the wrong type
10. ZeroDivisionError: raised when the second operand of a division or modulo operation is 0

Exceptions are dealt with by using the try/except statements, with statements that are potential sources of
exception appearing under try, and statements to be executed if an exception is raised, appearing under
except. Some of the approaches are given below:
1. try:
statements
except ExceptionName:
statements

2. try:
statements
except:
statements

3. try:
statements
except Exception1:
statements
except Exception2:
statements
:
except [ExceptionN]:
statments

4. try:

COURSE INSTRUCTOR: T. MIEBI


statements
except (Exception, Exception, …, Exception):
statements
5. try:
statements
except ExceptionName:
statements
finally:
statements

The statements after ‘finally’ are used to ensure there are not lose ends left after catching the
exception.

6. try:
statements
except ExceptionName:
statements
else:
statements

The statements after ‘else’ are executed if no exception is raised.

WORKING WITH FILES


This involves reading from and writing to files (text or binary). Steps followed are, open file, read from
or write to file, and finally close the file.

OPENING & CLOSING A FILE


open(‘filePath’, ‘mode’)

Important facts to note include:


1. File path is either absolute or relative
2. r preceding the string for the file path, prevents \ from performing its escaping function. For example:
>>> print('Hello\nEveryone')
Hello
Everyone
>>> print(r'Hello\nEveryone')
Hello\nEveryone
3. mode could be:
r -> read (raises exception if file is not found)
w -> write (creates file if missing or overwrites it if it exists)
a -> append (creates file if missing, or appends data to file content, if it exists)
Each letter above must be preceded by ‘b’ if the file is a binary file. In the absence of a preceding
letter or ‘t’ as preceding letter, the file involved is a text file.
4. If the mode is not included in open(), the file opened is a text file and it is opened for reading.
5. The function returns a file object, through which methods and functions for reading and writing are
used effectively.

Closing a file requires using invoking the method close() through the file object returned by open().

READING FROM A FILE


Methods involved are invoked from the file object. The examples provided would all be based on the text file
shown below:

COURSE INSTRUCTOR: T. MIEBI


1. read([int:n]): reads and returns the number of characters (text) or bytes (binary file) specified as
argument or the entire content of the opened file (string of texts from a text file, and a sequence of
bytes from a binary file), if there is no argument.
>>> f = open('[Link]')
>>> print([Link]())
do re mi
fa so la
ti do
>>> [Link]()

>>> f = open('[Link]', 'r')


>>> print([Link](5))
do re
>>> [Link]()

2. readline(): reads and returns a single line of data, including the newline character.
>>> f = open('[Link]')
>>> print([Link]())
do re mi

>>> [Link]()

3. readlines(): reads and returns each line of data in a list.


>>> f = open('[Link]', 'r')
>>> print([Link]())
['do re mi\n', 'fa so la\n', 'ti do']
>>> [Link]()

2 and 3 are clearer with text files.

It is also possible to get the content of a file using loops. This is as shown below:
f = open('[Link]', 'tr')
for data in f:
print(data, end = ‘’)
[Link]()

Output
do re mi
fa so la
ti do

WRITING TO A FILE
Methods involved in this are:
1. write(s): is called from the returned file object and s must be a string for text files and bytes for a
binary file. The bytes are returned from the function bytes(data). The data can one of the types
already known. If the data is a string, then a second argument on encoding type has to be included, for
example bytes(‘Hello’, ‘utf-8’).
2. print(data, file = fileObject): writes the data to the file object provided as a keyword argument. This
method only works for text files.

COURSE INSTRUCTOR: T. MIEBI


USING THE with OPERATOR
It is possible to write a program for file processing in such a way that the file is closed implicitly i.e.
the close() will not be invoked. Using the with operator requires that all file processing statements appear
indented under the file opening statement. Presented are two variants of a single program for this purpose.

Version 1
f = open(‘[Link]’)
data = [Link]()
print(data)
[Link]()

Version 2
with open(‘[Link]’) as f:
data = [Link]()
print(data)

UPDATING A FILE (READING AND WRITING)


It is possible to write to and read from a file in one opening. This is specified by ending the mode
argument used to open the file with +. Reading may require moving the file marker, if it is at the end of
the file due to a sequential write operation. The program below is written with the intention of appending
(writing from end of file) and reading from a file.

Code
f = open('[Link]', 'a+')

# move marker to the beginning


[Link](0)

print('ORIGINAL CONTENT')
print([Link]())

# Write new content to the file


print('do re re\nmi fa fa\nla so so', file = f)

# move marker to the beginning


[Link](0)

print('\nUPDATED CONTENT')
print([Link]())

[Link]()

Output
ORIGINAL CONTENT
do re mi
fa so la
ti do

UPDATED CONTENT
do re mi
fa so la
ti do
do re re
mi fa fa
la so so

COURSE INSTRUCTOR: T. MIEBI

You might also like