FCE246 Note (Intro. To Programming in Python
FCE246 Note (Intro. To Programming in Python
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.
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 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.
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.
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'>
With this relationship the name automatically produces the data. Try this on console:
>>> fullname = ‘James Peters’
>>> fullname
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)
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 ’
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
// 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 = ‘******’
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 => math.function(argument, …), math.function(), or math.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. math.trunc(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 +
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
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 expression 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(‘math.sqrt(3 ** 2 + 4 ** 2)’)
5.0 => √3 + 4
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
# Number of 1.6km in 14km = Number of miles in 14km
distance = 14 / 1.6;
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: 325932966
tion
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
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’))
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.
Note: The eval() function can receive a string made of 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.
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
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
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.
√
The formula for computing the area of a pentagon is = , where s is the length of the side. The side
can be computed using the formula = 2 sin , 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
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: '))
Output
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 = ($ − + ) + ( $ − + )
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
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.
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
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
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 OUTPUT
Areas of data formatting prior to display include among others, setting the space it occupies, controlling
its alignment within the space specified, controlling the number of decimal digits displayed in a fractional
number etc.
The syntax for how the formatting is specified is given below:
formatString & (value1, value2, …, valuen)
formatString contains 0 or more characters as well as a number of format specifiers matching the number of
values provided. A single format specifier is a combination of %, number, and a single alphabet i.e.
%NumberAlphabet. The most important pieces are the % and alphabet. The brackets for the values aren’t necessary
if it is just one value. Other important facts to note include:
1. The alphabet used depends on the type and format of the data to display.
d: to display value as a number in base 10 (decimal) form.
>>> print('%d' % (0b1101))
13
>>> print('%d' % (23.95))
23
>>> print(‘%d’ % (True))
1
x: to display value (int or bool) as a number in base 16 with alphabets in lower case.
>>> print(‘%x’ % (26))
1a
>>> print('%x' % (False))
0
X: to display value (int or bool) as a number in base 16 with alphabets in upper case.
>>> print(‘%X’ % (26))
1A
e: to display value (float, int, and bool) as a number in scientific/standard form with letter e.
>>> print('%e' % (34))
3.400000e+01
E: to display value as a number (float, int, and bool) in scientific/standard form with letter E.
>>> print('%E' % (34))
3.400000E+01
g: to display value as a number (float, int, and bool) like e does when its exponent in standard
form is less than -4, or like f does, otherwise.
>>> print(‘%g’ % (0.0001))
0.0001
>>> print(‘%g’ % (0.00001))
1e-05
G: to display value as a number (float, int, and bool) like E does when its exponent in standard
form is less than -4, or like f does, otherwise.
>>> print(‘%G’ % (0.0001))
0.0001
>>> print(‘%G’ % (0.00001))
1E-05
While all the examples above deal with just a value, the statement below shows one involving multiple
values:
>>> print('%s is %d.' % ('Score', 69))
Score is 69.
2. Integers or integer part of fractional numbers are used to specify the number of space (field width);
a data is to occupy when displayed. This space is in the terms of number of characters, and if it
smaller than the number of characters constituting the value, it is ignored. If the field width for a
value is enforced, no other value is displayed in it.
Example
>>> print('%d' % (68)); print('%10d' % (68))
68
68
Notice there are 8 spaces before 6 i.e.
6 8
Adding the two digits to the 8 spaces makes up the 10 character spaces making the field width.
3. The size of the number relative to 0 indicates the alignment of the data in the space provided. Positive
numbers indicate right alignment (default), while negative numbers indicate left alignment. The space
has to be bigger than what the data can occupy for its effect to be obvious.
Example
>>> print('#%-10d#' % 12); print('#%10d#' % 12)
#12 #
# 12#
4. Fractional part of numbers, when present, represents the number of fractional digits to display
(mathematical approximation is normally applied).
>>> print('%.3f' % 3.141592654)
3.142
5. It is not necessary to write the + when the number is positive, however when this is done, it means the
+ sign should be displayed with a positive number.
Example
>>> print('%+4d' % 24); print('%+7.4f' % 3.141592654)
+24
+3.1416
It was mentioned at the beginning of this section that the format string contains 0 or more characters. The
characters most popular with format string are escape character sequences. For example
>>> print('Score:\t%d' % 89)
Score: 89
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 the will enable us teach 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
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
if radius >= 0:
area = math.pi * 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 = math.pi * radius * radius
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:
/+0+ 1 /2$ /+/+ 1 /2$ 2
( = = and = = 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
# 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 + math.sqrt(disc)) / (2 * a)
r2 = (-b - math.sqrt(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
# Calculate y
y = (a * f - e * c) / 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:
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 − 1) . 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:
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.
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.
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.
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 4
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
# 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
# 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):
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)
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.)
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:
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:
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.
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.
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()
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 content (data or function) is through the module or the preferred_name
Example
1. Functions permute, and combine are both defined in the file function.py
2. These functions are then used in the program that comes after.
function.py
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 functions.py
r nPr nCr
0 1 1
1 3 3
2 6 3
3 6 1
Example 2
functions.py
from math import factorial
Output
This is a statement in functions.py
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))
for key, value in kwa.items():
print(key, value)
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 with symbol provided as argument, can be returned using the
迎
function ord(‘symbol’). For example ord(‘ ’) = 36814, ord(‘6’) = 54
FORMATTING STRINGS
The function format() provides a means of formatting a single value/data as a string. The function takes two
arguments (at most). The first is the value to be formatted, while the second is the format string. The format
string is very similar to the ones used for formatting program output. Important things to note include:
1. letters are used to indicate out the data is to be presented
2. integers or whole numbers are used to specify field width for the data
3. a single fractional digit is used to indicate the number of fractional digits to display through
approximation. This applies to numbers only
4. alignment within a field width is specified with > (right alignment/justification), < (left
alignment/justification), and ^ (center alignment)
5. unlike what we had earlier, alignment character appears first, numbers next, and the letter is last in
the format string.
FORMATS
Syntax of the format function is: format(value, formatString)
Below is a rundown of letters and characters (just one) used for indicating how value is to be presented.
1. b: to display integers in binary form.
print(format(10, 'b')) = 1010
print(format(0b1101, 'b')) = 1101
print(format(0o77, 'b')) = 111111
print(format(0xfce, 'b')) = 111111001110
4. x/X: to display integers in hexadecimal form, with uppercase letters when X (upper case) and lower case
letters when x (lower letter case).
print(format(30, 'x')) = 1e
print(format(30, 'X')) = 1E
5. f: to display a number in floating point form. If it is a number that is not decimal, gets converted
first to decimal.
print(format(True, 'f')) = 1.000000
print(format(45, 'f')) = 45.000000
print(format(0b1101, 'f')) = 13.000000
6. e/E: to display a number in standard form (in base 10), with the case of the letter in the output
dependent of the case of the letter in the format string.
print(format(250.23, 'e')) = 2.502300e+02
print(format(True, 'e')) = 1.000000e+00
print(format(True, 'E')) = 1.000000E+00
7. g/G: acts like f, of e for g, or E for G. It is e/E if the exponent of the value in standard form is
less than -4, otherwise it uses f.
print(format(0.00001, 'g')) = 1e-05
print(format(0.00001, 'G')) = 1E-05
print(format(0.0001, 'g')) = 0.0001
9. %: displays a number in percent (the value is multiplied by 100, with % appended to the result).
print(format(True, '%')) = 100.000000%
print(format(0b01, ‘%’) = 100.000000%
print(format(0.05, ‘%’) = 5.000000%
FIELD WIDTH
Specifying field width simply requires adding an integer to the format string. The number represents the
number of characters that can occupy the space to be created.
print(format('Hi', 's'), end = '.\n') = Hi.
print(format('Hi', '10s'), end = '.\n') = Hi .
Note: It is also possible to add + to these numbers to have it displayed in the number.
print(format(0.1556, '+.2f')) = +0.16
print(format(45.235, '+5.2f')) = +45.23
ALIGNMENT/JUSTIFICATION
For alignment/justification within an oversized field width, numbers are justified to the right by default,
while strings are justified to the left by default. If these defaults are not desired, then using <, or > will
provided the justification desired.
print(format('Hi', '20s'), end = '.') = Hi .
print(format(15, ‘20d’), end = ‘.’) = 15.
print(format('Hi', '20s'), end = '.') = Hi.
print(format(15, '<20d'), end = '.') = 15 .
print(format(15, '^20d'), end = '.') = 15 .
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’
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
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. s.capitalize() 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. s.center(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. s.count(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
'banana'.count('na', 2, 5) = 1
'banana'.count('an', 4) = 0
4. s.endswith(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. s.expandtabs(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. s.find(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
s.rfind(t, start, end) is similar to s.find(), but returns the rightmost position.
'coconut'.rfind('o') = 3
'coconut'.rfind('o', 0, 3) = 1
'coconut'.rfind('u', 0, 3) = -1`
7. s.index(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
s.rindex(t, start, end) is similar to s.index(), but returns the rightmost position.
'coconut'.rindex('o') = 3
8. s.isalnum() 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. s.isalpha() returns True if s is not empty, and all characters in it are alphabets.
'abc'.isalpha() = True
'ab12'.isalpha() = False
10. s.isdigit() returns True if s is not empty, and every character in it is a digit.
'123'.isdigit() = True
'12ab'.isdigit() = False
12. s.islower() 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. s.isspace() returns True if s is nonempty and every character in s is a whitespace character.
'\t\n'.isspace() = True
'a\tb'.isspace() = False
14. s.istitle() 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. s.isupper() 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. s.join(sequence) returns a string in which s is planted between every item (character) in the sequence.
'*'.join('HELLO') = 'H*E*L*L*O'
17. s.ljust(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********'
s.rjust(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. s.partition(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')
s.rpartition(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. s.replace(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. s.split(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']
s.rsplit(t, n) is similar to s.split(), but splits from right to left (effective with n that is less
than the maximum split possible)
'banana'.rsplit('a', 2) = ['ban', 'n', '']
22. s.splitlines(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. s.startswith(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. s.strip(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'
s.lstrip(ch) similar to s.strip() but only removes characters from the left.
' Hello '.lstrip() = 'Hello '
'***Hi***'.lstrip('*') = 'Hi***'
s.rstrip(ch) similar to s.strip(), but only removes characters from the right.
' Hello '.rstrip() = ' Hello'
'***Hi***'.rstrip('*') = '***Hi'
26. s.swapcase() returns a version of s in which uppercase characters are lowercase, while lowercase
characters are uppercase.
'hI'.swapcase() = 'Hi'
27. s.title() 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. s.zfill(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'
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.
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:
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
3. lst.extend(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']
4. lst.index(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
5. lst.insert(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']
6. lst.pop() returns and removes the rightmost element from lst consequently reducing its length by 1.
lst = ['m', 'a', 't', 'e']
lst.pop() = 'e'
lst = ['m', 'a', 't'] # lst after executing pop()
8. lst.remove(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
lst.remove('a')
lst = ['d', 'a', 'm'] # lst after remove() got executed
10. lst.sort() 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
lst.sort()
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.
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
lst2.extend(lst1)
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 = False
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)
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. s.add(v) adds to the set s.
s = {2, 3, 4}
s.add(‘hi’)
print(s) # s = {2, 3, 4, ‘hi’}
3. s.issubset(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. s.issuperset(t) / s >= t: returns True if s is a superset of t (s contains all elements in t and maybe
more)
{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. s.union(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. s.pop() returns and removes a random element from s. It returns KeyError if unsuccessful.
>>> s = {1, 3, 5, 7}
>>> s.pop()
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. s.update(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
s.update(‘hi’) => good
s.update([3, 4]) => good
s |= ‘hello’ => bad
FROZEN SET
This is a set which becomes immutable after creation. Only a select group of set methods and operators
therefore apply. Creating a frozen set requires using the function below. The function takes 0 or 1 argument.
frozenset(): creates an empty frozen set
frozenset(argument): creates a frozen set from the argument supplied.
copy(), difference(), -, intersection(), &, isdisjoint(), issubset(), <=, <, issuperset(), >=, >,
symmetric_difference(), ^, union(), and | are the methods and operators of sets that can be applied to frozen
sets.
If a set and a frozen set are the operands of a binary operator, the result obtained is of the same type as
the left operand. The example below shows all of this:
>>> s = frozenset('abc')
>>> t = {1, 2, 3}
>>> u = s | t
>>> type(s)
<class 'frozenset'>
>>> type(u)
<class 'frozenset'>
>>> u = t | s
>>> type(t)
<class 'set'>
>>> type(u)
<class 'set'>
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
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. d.clear() removes all elements from d
>>> d = {1: True, 2: False}
>>> d
{1: True, 2: False}
>>> d.clear()
>>> d
{}
3. d.get(key) returns the value associated with key in d, or None (no value) if key isn’t in d.
>>> d.get(1)
True
8. d.pop(k, v) returns the value associated with k, and removes it, or returns v if k is not in d
>>>>d.pop(4, 'Missing')
'Missing'
9. d.popitem() returns and removes an arbitrary key-value pair from d, or raises KeyError exception if d is
empty
>>> d.popitem()
(1, True)
10. d.setdefault(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.
>>> d.setdefault(1, True)
False
>>> d.setdefault(3, True)
True
>>> d
{1: False, 3: True}
11. d.update(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}
>>> d.update(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, '=', grdPts.get(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 grdPts.items():
>>> 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 grdPts.items():
>>> print(item[0], '=', item[1])
A = 5
B = 4
C = 3
D = 2
F = 0
PYTHON COMPREHENSIONS
Manual initialization of a collection type with a big length in programs, is a tough task. Python provides
special looping and branching techniques called COMPREHENSIONS.
LIST/SET COMPREHENSIONS
[expression for item in collection]
Expression is either equal to item or contains item (member of the list).
Example
>>> [yr for yr in range(1992, 2017)] # Every year from 1992 to 2016
[1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]
for-statements in comprehensions can be more than one, in which case they represent nested loops. This can be
used to make a multidimensional list become one list.
This is as shown below:
>>> l1 = [[1, 2, 3, 4, 5, 6], ['a', 'b', 'c', 'd']]
>>> l2 = [e for i in l1 for e in i]
>>> print(l2)
[1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd']
These same comprehensions can be used for sets. The only thing to note is data duplicates will appear as one.
DICTIONARY COMPREHENSIONS
{keyExpression:valueExpression for key, value in collection}
{keyExpression:valueExpression for key, value in collection if condition}
Examples
>>> {c: ord(c) for c in 'aeiou'}
{'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117}
{chr(i): i for i in range(97, 123) if i not in (97, 105, 101, 117, 111)}
{'b': 98, 'c': 99, 'd': 100, 'f': 102, 'g': 103, 'h': 104, 'j': 106, 'k': 107, 'l': 108, 'm': 109, 'n': 110,
'p': 112, 'q': 113, 'r': 114, 's': 115, 't': 116, 'v': 118, 'w': 119, 'x': 120, 'y': 121, 'z': 122}