GET211 Note (Baisc Python 3 Programming)
GET211 Note (Baisc Python 3 Programming)
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.
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.
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.
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.
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.
>>> 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'>
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:
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
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
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)
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 ’
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
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
16. ( )Space Display space to the left of positive numbers, where the minus is standing for
negative numbers.
f"{25: }\n{-25: }"
∥
25
-25
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#
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#
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
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 = ‘******’
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
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]
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
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.
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
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
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
Output
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
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’))
Output
Enter two integers separated by comma: 3, 4
3 4
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)
Output
Enter diameter: 2.5
Enter height: 6.5
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
Output
Solution
# Request for and save 4-digit interger
numb = int(input('Enter a 4-digit integer: '))
Output
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:
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
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
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
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
if radius >= 0:
area = [Link] * radius * radius
print('Area of circle is', area)
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
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: '))
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:
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
# 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.
Code
a, b, c, d, e, f = eval(input('Enter a, b, c, d, e, f: '))
# Test discriminant
if disc == 0:
print('The equa tion has no solution')
else:
# Calculate x
x = (e * d - b * f) / disc
# Display x and y
print('x is', x, 'and y is', y)
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:
(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:
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.
# 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
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
Output 1
0 1 2 3 4
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.
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 = 0
for n in range(50000, 0, -1):
sum += 1/n
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
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
# Check for sentinel value to know whether to compute and repeat request
while value >= 0:
# Take count
count += 1
# Update sum
sum += value
# 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)
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):
Output (Sections)
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
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.)
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:
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’
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
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
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'
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'
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
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
# Display volume
print('\nVolume of cone is', getVolume(d, h))
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.
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.
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
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:
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
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
# 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
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
n = 10
print('n =', n)
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
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
Output
This is a statement in [Link]
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))
def checkIfPrime(numberToCheck):
for x in range(2, numberToCheck):
if(numberToCheck%x == 0):
return False
return True
import prime
answer = [Link](19)
print(answer)
Result
True
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
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:
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
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()
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)
print('\nAFTER ASSIGNMENT')
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
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)
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
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.
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)
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’}
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)
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}
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}
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}
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}
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
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
{}
3. [Link](key) returns the value associated with key in d, or None (no value) if key isn’t in d.
>>> [Link](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)
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]():
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:
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
Closing a file requires using invoking the method close() through the file object returned by open().
2. readline(): reads and returns a single line of data, including the newline character.
>>> f = open('[Link]')
>>> print([Link]())
do re mi
>>> [Link]()
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.
Version 1
f = open(‘[Link]’)
data = [Link]()
print(data)
[Link]()
Version 2
with open(‘[Link]’) as f:
data = [Link]()
print(data)
Code
f = open('[Link]', 'a+')
print('ORIGINAL CONTENT')
print([Link]())
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