Python Note 1
Python Note 1
Outline
The concept of problem and problem solving strategies
The role of algorithm in problem solving process
Concept and properties of algorithms
Algorithm implementation strategies
Python implementation
Definition: A problem is a situation that presents difficulty or complexity. Hayes (1980) defines
problem as a gap between where you are now and where you want to be, and you don’t know
how to find a way to cross that. Problems come from many shapes and sizes, for instances;
something did not work as it should and you don’t know how or why. Something you need is
unavailable, and something must be found to take its place.
Problem Solving: Problem Solving is the sequential process of analyzing information related to
a given situation and generating appropriate response options. Problem involves a number of
strategies; these are discussed below;
Problem-Solving Strategies
1. Solve by Analogy
The first strategy for solving a problem is through thorough analysis of the problem to identify
different ways of solving it and to evaluate each of these methods. The idea here is to search an
appropriate solution to the problem under consideration. The end result of this strategy is a broad
overview of the sequence of operations that are to be carries out to solve the given problem.
2. Means-Ends Analysis
This strategy identifies the beginning state and the ending state of a given problem; the problem
is to define a set of actions that can be used to get from one to the other. Once you’ve narrowed
down the set of actions, you have to work out the details. It may help to establish intermediate
goals that are easier to meet than the overall goal.
1
3. Divide and Conquer
This strategy often breaks down large problems into smaller units that are easier to handle.
Sometimes each of these smaller units are handled by different categories of professional.
See figure 1.16 for details.
There are 6 steps that you should follow in order to solve a problem:
1. Understand the Problem
2. Formulate a Model
3. Develop an Algorithm
4. Write the Program
5. Test the Program
2
6. Evaluate the Solution
3
computational model: Average = (x1 + x2 + x3 + … + xn) / n where the result will be a number
from 0 to 100.
class SumAverage {
public static void main(String[] args) {
int[] numbers = {2, 10, 0, 5, 12, 25, 22, 9, 8, 12};
int sum = 0;
Double average;
int arrayLength = numbers.length;
for (int i = 0; i < arrayLength; i++) {
sum = sum + numbers[i];
average = sum /arrayLength;
System.out.println("Average = " + average);
4
STEP 5: Test the Program:
Once you have a program written that compiles, you need to make sure that it solves the problem
that it was intended to solve and that the solutions are correct. Running a program is the process
of telling the computer to evaluate the compiled instructions. If a program executes correctly, the
right output is displayed. It is possible however, that your program works correctly for some set
of data input but not for all. If the output of your program is incorrect, it is implies that you did
not convert your algorithm properly into a program. It is also possible that you did not produce a
proper algorithm back in step 3 that handles all situations that could arise.
All problems that arise in a program are known as bugs. Bugs are errors with a program that
cause it to stop working or produce incorrect or undesirable results. You should fix as many bugs
in your program as you can find. To find bugs effectively, test your program with many test
cases (called a test suite). It is also a good idea to have others test your program because they
may think up situations or input data that you may never have thought of. The process of finding
and fixing errors in a code is called debugging and it is often very time-consuming.
STEP 6: Evaluate the Solution:
Once your program produces a result that seems correct, you need to re-consider the original
problem and make sure that the answer is formatted into a proper solution to the problem. It is
often the case that you realize that your program solution does not solve the problem the way
that you wanted it to. You may realize that more steps are involved. For example, if the result of
your program is a long list of numbers, but your intent was to determine a pattern in the numbers
or to identify some feature from the data, then simply producing a list of numbers may not
suffice. There may be a need to display the information in a way that helps you visualize or
interpret the results with respect to the problem. Perhaps a chart or graph is needed. It is also
possible that when you examine your results, you realize that you need additional data to fully
solve the problem. Or, perhaps you need to adjust the results to solve the problem more
efficiently (e.g., your game is too slow).
5
Definition: An algorithm is a finite set of instructions that, if followed, accomplishes a particular
task. In addition, all algorithms must satisfy the following criteria:
1. Input. Algorithm must be able to accept some set of data to work on. There are zero or
more quantities that are externally supplied.
2. Output. Must be capable of producing result or set of results. At least one quantity is
produced.
3. Definiteness. Each instruction is clear and unambiguous.
4. Finiteness. Algorithm must terminate after a finite number of steps.
5. Effectiveness. Every algorithm should be able to produce a reliable and desirable result.
Types of Algorithms
Algorithm types we will consider include:
1. Simple recursive algorithms
2. Backtracking algorithms
5. Greedy algorithms
8. Randomized algorithms
6
Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming
language. It includes features of C and Java to provide style of writing an elegant code. Python is
available on a wide variety of platforms such as Windows, Mac, Linux etc. Python was
developed in the early 1990’s by Guido van Rossum and named after a TV Show called ‘Monty
Python’s Flying Circus’ and not after Python-the snake.
Used of Python
Python can be used on a server to create web applications (e,g Instagram, YouTube).
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
……………………..
Variables
Variables are containers for storing data values. One of the major purposes of a variable is to
remember a value from one part of a program so that it can be used in another part of the
program. For instance, if we perform a calculation and need to use the result of the calculation in
several places in the program, then the result is stored a special character/alphanumeric
combination, called variable for later use.
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume, totally etc).
7
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Creating Variables
Python has no command for declaring a variable. A variable is created the moment you first
assign a value to it.
Myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
x=5
y = "John"
print(x) print(y)
Case-Sensitive
A = "Sally"
a = 4 # A will not overwrite a
8
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x) # output value of x = Orange
print(y) # output value of y = Banana
print(z) # output value of z = Cherry
Unpack a Collection
If there is a collection of values in a list, tuple etc. Python allows it extractio into different
variables. E,g;
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x) # output value of x = apple
print(y) # output value of y = banana
print(z) # output value of z = cherry
9
Python Data Types
Data Types are data formats stored in variables of different kinds. Python has the following data
types built-in by default:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type:bool
Binary Types: bytes, bytearray, memoryview
Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
10
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
11
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
12
Python Logical Operators
Logical operators are used to combine conditional statements
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
is not Returns True if both variables are not the same object x is not y
13
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
14
A simple python Program
#This program demonstrates simple input and output style in python
num1 = 20
Name = input (‘Enter fist name’)
Print (‘My name is:’, Name)
num2 = eval(input(‘Enter a number’)
Print (‘The Name is: ‘, Name)
Print (‘the sum of the numbers is:’, num1+ num2)
Print (‘the average of the numbers is:’, (num1+ num2)/2)
List
This is a collection of items which is ordered and changeable and allows duplicate items
(members) at some point. Lists are containers that hold objects in a given order. These items can
be added or remove from the sequence. Each element of the sequence is assigned a number,
called the index with the first index been 0 (zero). List is written in a sequence separated by
commas between expressions.
Creating a List
The syntax is:
lst1 = [ ] # lst1 is the name of the list
Examples of List
15
Accessing list items
16
Tuple
Tuples are used to store multiple items in a single variable. It is an immutable list and cannot be
changed in any way once it is created. Characteristics features of Tuples are:
tup2 = (6,5,4,3,2,1)
17
18
Set
Sets are used to store multiple items in a single variable. A set is a collection which is
both unordered, unindexed, unchangeable and do not allow duplicate values. Sets are written
with curly brackets.
Example:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Dictionary
Dictionary is like a list but in a general form. It is a mapping between a set of indexes or keys
with a set of values, where each key maps to a value. A combination of a key and its value is
called a key-value pair or item. In the Python dictionary, each key is separated by a colon (:)
from its values. Commas separate all the items, and the whole dictionary is enclosed within '{'
and '}'. In the dictionary, all the keys are unique with data type as strings, tuples, or numbers,
and the values can be of any of these three types.
Conditional Statements
19
Conditional statements are utilized in decision making, preferably when we prefer to execute a
piece of code only when certain conditions are met. In the nutshell, a conditional statement
directs the order of execution of the statements.
Types
(1) If Statement (2) if else statement (3) elif statement.
1. If Statement: It consists of a Boolean expression which results are either TRUE or
FALSE, followed by one or more statements.
Syntax:
if expression:
#execute your code
#execute your code
Example Program
a = 15
if a > 10:
print ("a is greater")
20
2. if else statement: It also contains a Boolean expression. The if the statement is followed
by an optional else statement and if the expression results in FALSE, then else statement
gets executed. It is also called alternative execution in which there are two possibilities of
the condition in which any one of them will get executed
syntax:
if expression:
#execute your code
else:
#execute your code
Example program
a = 15
b = 20
if a > b:
print ("a is greater")
else:
print ("b is greater")
21
3. elif statement: A keyword used in Python to replacement “else if” statement and to
place another condition in the program. This is called chained conditional
Syntax:
if expression:
#execute your code
elif expression:
#execute your code
else:
#execute your code
Example program
a = 15
b = 15
if a > b:
print("a is greater")
elif a == b:
print("both are equal")
else:
print("b is greater")
22
4. Nested Statements: We can implement if statement and or if-else statement inside
another if or if - else statement. Here more than one if conditions are applied & there can
be more than one if within elif.
Syntax:
if <expr1>:
<statement1>
# Executes statement1 when expr1 is True
if <expr2>:
<statement2>
# Executes statement2 when expr2 is True
# Inner if-block ends here
# Outer if-block ends here
Example: In the following example we implement the nested if-statement on a program where
the user inputs a number and checks different conditions with regards to that number.
a = 10
if(a>5):
print("Inside initial if")
print("Number is greater than 5")
if(a>=10):
23
print("Inside first nested if")
print("Number is greater than or equal to 10")
if(a>=15):
print("Inside second nested if")
print("Number is greater than or equal to 15")
print("Outside second nested if")
print("Outside second nested if")
print("Outside initial if")
Control Statements
Control statements in python are used to control the order of execution of the program based on
the values and logic. They are responsible for managing the flow in which loops get executed.
The order in which the specified set of statements need to be executed can be effectively
governed using these control statements. The major set of control statements are: For Loops,
While Loops, Break, Continue and Pass
1. For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string). With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Example: Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String: Even strings are iterable objects, they contain a sequence of
characters:
Example: Loop through the letters in the word "banana":
for x in "banana":
print(x)
24
2. While Loops
The while Loop execute a set of statements as long as a condition is true. The while loop requires
relevant variables to be ready, in this example we need to define an indexing variable, i, which
we set to 1.
Example: Print i as long as i is less than 6:
i= 1
while i < 6:
print(i)
i += 1
Note: If i is not incremented the loop will continue forever. This may result in system freeze
While loop with break Statement: With the break statement we can stop the loop even if the
while condition is true:
Example: Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
25
The While Loop with else Statement
With the else statement we can run a block of code once when the condition is no longer true:
Example: Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
3. Break
The break Statement is used to stop the loop before it get to the last item.
Example: Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example: Exit the loop when x is "banana" and print the iterated item.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
4. Continue
The continue Statement is used to stop the current iteration of the loop, and continue with the
next item of the list.
Example: Do not print banana on the list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
26
continue
print(x)
5. Pass
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
Using the start parameter:
27
Functions
You may be familiar with the mathematical concept of a function. In mathematics, a function is a
relationship or mapping between one or more inputs and a set of outputs. A function is typically
represented like this:
Here, f is a function that operates on the inputs x and y. The output of the function is z. However,
programming functions are much more generalized and versatile than this mathematical
definition. In fact, appropriate function definition and use is so critical to proper software
development that virtually all modern programming languages support.
Types of Functions
1. Built-in functions: These are pre-defined functions that are readily available for use to
perform specific task. They are functions that readily come with Python to be used by users.
Some of these functions are listed below;
28
Function Name Actions
Python abs() returns absolute value of a number
29
Python hasattr() returns whether object has named attribute
30
Python round() rounds a number to specified decimals
Result:
31
2. User-Defined Functions (UDFs): These are functions that are defined by the users to do
certain specific task. They also referred to as user-defined functions.
1. User-defined functions help to decompose a large program into small segments which
makes program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include these codes and
execute when needed by calling that function.
3. Programmars working on large project can divide the workload by making different
functions.
6. One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).
32
Example
def add_numbers(x,y):
"""This function accept two numbers as a parameters and add them"""
sum = x + y
return sum
x=5
y=6
print("The sum is", add_numbers(x, y))
Calling a Function
Function Calling means executing the function that have been defined, either directly from the
Python prompt or through another function. To call a function, use the function name followed
by parenthesis:
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
#calling the function
hello()
Arguments / Parameters
A parameter is the variable listed inside the parentheses in the function definition while an
argument is the value that is sent to the function when it is called. Arguments are specified after
the function name, inside the parentheses. You can add as many parameter /arguments as you
want, just separate them with a comma. By default, a function must be called with the correct
number of arguments, meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
33
Function Passing by Parameters/Passing by Value
Functions can received input either through parameters or by values. Parameters are variables
that hold values to be passed into a function whereas values are the quantities to be passed into a
function for proper operations.
def add_numbers(x,y):
"""This function accept two numbers as a parameters and add them"""
sum = x + y
x =5
y=6
return sum
#passing parameters x and y as inputs
print("The sum is", add_numbers(x, y))
def add_numbers(x,y):
"""This function accept two numbers as a parameters and add them"""
sum = x + y
return sum
#passing value 5 and 6 in place of parameters x and y
print("The sum is", add_numbers(5, 6))
34
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable. Scope of Variables is therefore the life span of variable
in a given program. The scope of a variable determines the portion of the program where you can
access a particular identifier.
There are two basic scopes of variables in Python;
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope. This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought into
scope. Following is a simple example −
35
Class, Methods and Statics Methods
Definition of a class
A class represents a collection of objects having same characteristic properties that exhibit
common behavior. It gives the blueprint or description of the objects that can be created from it.
Creation of an object as a member of a class is called instantiation. Thus, object is an instance of
a class.
A class in Python can be defined using the class keyword. Syntax for creating python class is
given below;
class <ClassName>:
<statement1>
<statement2>
.
.
<statementN>
1. Class Attributes
2. Constructor
3. Instance Attributes
36
4. Properties
5. Class Methods
Class Attributes
Class attributes are the variables defined directly in the class that are shared by all objects of
the class. Class attributes can be accessed using the class name as well as using the objects.
class Student:
schoolName = 'Benue state University'
Constructor
Most classes will have a method called __init__. The underscores indicate that it is a special kind
of method. It is called a constructor, and it is automatically called when you create a new object
from your class. The constructor is usually used to set up the class’s variables. the constructor
method is invoked automatically whenever a new object of a class is instantiated and must
have a special name __init__() and a special parameter called self. The first parameter of each
method in a class must be the self , which refers to the calling object. However, you can give any
name to the first parameter, not necessarily self.
The __init__() Function
To understand the meaning of classes we have to understand the built-in __init__() function. All
classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Instance Attributes
37
Instance attributes are attributes or properties attached to an instance of a class. Instance
attributes are defined in the constructor. The following example defines instance
attributes name and age in the constructor.
Object
Objects are instantiations of classes; classes define the type of certain objects. Let us create a
method in the Person class:
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36) #p1 is an object
p1.myfunc()
Class Methods
A program can be very long and complex. To manage such a complexity, it is necessary to
realize programs in a modular way, called methods. A method is a program module that contains
series of statements to carry out a specific task. To execute a method, you invoke or call it from
38
another method; the calling method makes a method call, which invokes the called method. Any
class can contain an unlimited number of methods, and each method can be called unlimited
number of times. A method can be defined in a class using the def keyword. Each method
must have the first parameter, generally named as self, which refers to the calling instance.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def displayInfo(self): # class method
print('Student Name: ', self.name,', Age: ', self.age)
39