Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Python Note 1

Uploaded by

peterodey067
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python Note 1

Uploaded by

peterodey067
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

CMP 201: Computer programming I (3 Unit)

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.

4. The Building-Block Approach


Another way of attacking a large problem is to see if any solutions for smaller pieces of the
problem exist. It may be possible to put some of these solutions together end to end to solve
most of the big problem. You look at the big problem and see that it can be divided into
smaller problems for which solutions already exist. Solving the big problem is just a matter
of putting the existing solutions together.

5. Algorithmic Problem Solving


Algorithm is strategy for problem solving which makes the computer transform, manipulate,
calculate, or process the input data to produce the desired output. An algorithm is a finite set of
instructions that, if followed, accomplishes a particular task.

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

STEP 1: Understanding the Problem:


The first step to solving any problem is to make sure that you understand the problem that you
are trying to solve. This step requires noting the following:
 What input data/information is available ?
 What does it represent ?
 What format is the data/information ?
 Is anything missing ?
 Do I have everything that I need ?
 What output information can be produced ?
 how will the result look like (text, picture, graph etc)
Consider this simple problem: Calculate the average grade for all students in a class.
In this example, you can understand that the inputs are scores from 0 to 100. We need to
understand the format of the scores, in this case integers in order to solve the problem. We also
need to consider missing scores. i.e students that were away during the test, is there need
include then in our average (i.e., they received 0) or ignore them when computing the average ?
We also need to understand what the output should be. Finally, we should understand the kind of
processing that needs to be performed on the data. This leads to the next step.

STEP 2: Formulate a Model:


This step is based on the processing part of the problem. Many problems may need to be broken
down into smaller parts (sub problems) that require some kind of simple mathematical
computations in order to process the data. In our average example, we are going to compute the
average of the incoming grades. So, we need to know the model (or formula) for computing the
average of a bunch of numbers. If there is no such “formula”, we need to develop one. Often,
however, the problem breaks down into simple computations that we well understand.
Sometimes, we can look up for certain formulas in books or online to enable solving the
problem.
In order to come up with a model, we need to fully understand the information available to us.
Assuming that the input data is a bunch of integers x1,x2,…,xn, we can use the following

3
computational model: Average = (x1 + x2 + x3 + … + xn) / n where the result will be a number
from 0 to 100.

STEP 3: Develop an Algorithm:


Now that we understand the problem and have formulated a model, it is time to come up with a
precise plan of what we want the computer to do. An algorithm is a precise sequence of
instructions for solving a problem. Algorithms will be discussed in detail later in this course. An
example algorithm for the average example is shown below;
Algorithm: DisplayAvg

1. set the sum of the scores values to 0.


2. Input score x1 … xn
3. repeat n times {
4. get score xi
5. add xi to the sum
}
6. compute the average to be sum / n.
7. print the average.

STEP 4: Write the Program:


Now that we have a precise set of steps for solving the problem, we can transform the algorithm
from step 3 into a set of instructions that can be understood by the computer. Writing a program
is often called "writing code" or “implementing an algorithm”. So the code (or source code) is
actually the program itself. The program is shown below;

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

3. Divide and conquer algorithms

4. Dynamic programming algorithms

5. Greedy algorithms

6. Branch and bound algorithms

7. Brute force 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.

First Python Program

……………………..

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

Rules for Python Variables

 A variable name must start with a letter or an underscore character


 A variable name cannot start with a number

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.

Valid variable names

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

Variable names are case-sensitive.

A = "Sally"
a = 4 # A will not overwrite a

Multi Words Variable Names


Variable names with more than one word can be difficult to read. There are several techniques
you can use to make them more readable:
Camel Case: Each word, except the first, starts with a capital letter: myVariableName = "John"
Pascal Case: Each word starts with a capital letter: MyVariableName = "John"
Snake Case:
Each word is separated by an underscore character: my_variable_name = "John"

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

One Value to Multiple Variables


The same value can be assigned to multiple variables in one line as below:
x = y = z = "Orange"
print(x) # output value of x = Orange
print(y) # output value of y = Orange
print(z) # output value of z = Orange

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

Getting the Data Type


Data type of any object is gotten using the type () function: e.g data type of variable x can be
printed as:
x=5
print(type(x))

Python Operators

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y

10
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

= 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

&= x &= 3 x=x&3

11
|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

12
Python Logical Operators
Logical operators are used to combine conditional statements

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements x < 5 or x < 4


is true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same object x is y

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:

Operator Description Example

in Returns True if a sequence with the specified value is present in x in y


the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

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

Python Collections (Arrays)


This is a collection of similar items which can ordered and changeable. There are four collection
data types in the Python programming language: List, Tuple, Set and Dictionary .
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.

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

lst2 = [expression1 , …. , expression_N]

Examples of List

lst1 = ['computersc', 'IT', 'CSE'];


lst2 = [1993, 2016];
lst3 = [2, 4, 6, "g", "k", "s"];

15
Accessing list items

Elements of a List can be assed using;

i. len(L): which returns the number of items present in the list.


ii. L[i]: represents the item at index i.
iii. L[i:j]: returns new list containing objects within 'i' and 'j'.

Program to Access items of a list

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:

 Tuples are defined in the same way as lists.


 They are enclosed within parenthesis and not within square braces.
 Elements of the tuple must have a defined order.
 Negative indices are counted from the end of the tuple, just like lists.
 Tuple also has the same structure where commas separate the values.
Example:
tupl1 = ('computersc', 'IT', 'CSE')

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

The While Loop with continue Statement


With the continue statement we can stop the current iteration, and continue with the next:
Example: Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

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


To loop through a set of code a specified number of times, we can use the range() function.
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
Example: Using the range() function:
for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

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:

for x in range(2, 6):


print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)

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.

In programming, function is defined as:


1. A self-contained block of code that encapsulates a specific task or related group of tasks.
2. A piece of code written to carry out a specified task. To carry out that specific task, the
function might or might not need multiple inputs.
3. A group of related statements that performs a specific task.
4. A sub-program that performs a specific task or solve part of a general problem.
In general, functions in programming are used to bundle a set of instructions to be used
repeatedly. Functions also help to break down larger program into smaller and modular chunks.
As our program grows larger and larger, functions make it more organized and manageable.
In other programing languages, functions may be referred to as: Subroutines, Procedures,
Methods or Subprograms.

Types of Functions

There are three types of functions in Python:

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

Python all() returns true when all elements in iterable is true

Python any() Checks if any Element of an Iterable is True

Python ascii() Returns String Containing Printable Representation

Python bin() converts integer to binary string

Python bool() Converts a Value to Boolean

Python bytearray() returns array of given byte size

Python bytes() returns immutable bytes object

Python callable() Checks if the Object is Callable

Python chr() Returns a Character (a string) from an Integer

Python classmethod() returns class method for given function

Python compile() Returns a Python code object

Python complex() Creates a Complex Number

Python delattr() Deletes Attribute From the Object

Python dict() Deletes Attribute From the Object

Python dict() Creates a Dictionary

Python dir() Tries to Return Attributes of Object

Python divmod() Returns a Tuple of Quotient and Remainder

Python enumerate() Returns an Enumerate Object

Python eval() Runs Python Code Within Program

Python exec() Executes Dynamically Created Program

Python filter() constructs iterator from elements which are true

Python float() returns floating point number from number, string

Python format() returns formatted representation of a value

Python frozenset() returns immutable frozenset object

Python getattr() returns value of named attribute of an object

Python globals() returns dictionary of current global symbol table

29
Python hasattr() returns whether object has named attribute

Python hash() returns hash value of an object

Python help() Invokes the built-in Help System

Python hex() Converts to Integer to Hexadecimal

Python id() Returns Identify of an Object

Python input() reads and returns a line of string

Python int() returns integer from a number or string

Python isinstance() Checks if a Object is an Instance of Class

Python issubclass() Checks if a Class is Subclass of another Class

Python iter() returns an iterator

Python len() Returns Length of an Object

Python list() creates a list in Python

Python locals() Returns dictionary of a current local symbol table

Python map() Applies Function and Returns a List

Python max() returns the largest item

Python memoryview() returns memory view of an argument

Python min() returns the smallest value

Python next() Retrieves next item from the iterator

Python object() creates a featureless object

Python oct() returns the octal representation of an integer

Python open() Returns a file object

Python ord() returns an integer of the Unicode character

Python pow() returns the power of a number

Python print() Prints the Given Object

Python property() returns the property attribute

Python range() return sequence of integers between start and stop

Python repr() returns a printable representation of the object

Python reversed() returns the reversed iterator of a sequence

30
Python round() rounds a number to specified decimals

Python set() constructs and returns a set

Python setattr() sets the value of an attribute of an object

Python slice() returns a slice object

Python sorted() returns a sorted list from the given iterable

Python staticmethod() transforms a method into a static method

Python str() returns the string version of the object

Python sum() Adds items of an Iterable

Python super() Returns a proxy object of the base class

Python tuple() Returns a tuple

Python type() Returns the type of the object

Python vars() Returns the __dict__ attribute

Python zip() Returns an iterator of tuples

Python __import__() Function called by the import statement

Example: program using built-in function

fruits = ["apple", "banana", "cherry"]


# printing the elements of the array is:
for x in fruits:
print(x)
#printing length of the array
print(len(fruits))

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.

Advantages of 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.

Syntax for User-Defined Function


def function_name(parameters):
"""docstring"""
statement(s)
return [expression]

Above shown is a function definition that consists of the following components.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.

4. A colon (:) to mark the end of the function header.

5. Optional documentation string (docstring) to describe what the function does.

6. One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.

32
Example

# Program to illustrate the use of user-defined functions

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

Result: The sum is 11

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.

Example: program to illustrate inputs passing by parameters

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

Example: program to illustrate inputs passing by values

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

The Anonymous Functions


These functions are called anonymous or lambda because they do not have specific name and
even not declared in the standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.
 Lambda functions can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression
 Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1,arg2,.....argn]:expression

Following is the example to show how lambda form of function works −

34
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2

# Now you can call sum as a function


print ("Value of total:", sum( 10, 20 ))
print ("Value of total:", sum( 20, 20 ))

When the above code is executed, it produces the following result −


Value of total : 30
Value of total : 40

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 −

diff = 0 # This is global variable.

def sum( arg1, arg2 ): # Function definition


total=0 # local variable
# Add both the parameters and return them.
total = arg1 + arg2; # Here total is local variable.
diff= arg1 - arg2; # Here diff is a global variable.
return diff, total
# Now you can call sum function
print ("the sum is:”, sum(30,10) “and the difference is:”, diff)

When the above code is executed, it produces the following result −


the sum is: 40, the difference is: 20

35
Class, Methods and Statics Methods

Python is an object oriented programming language. Unlike procedure oriented programming,


where the main emphasis is on functions, object oriented programming stresses on objects. Class
names usually start with a capital. An object is simply a collection of data (variables) and
methods (functions) that act on those data.

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.

The constituents of a class are −


 A set of attributes for the objects that are to be instantiated from the class. Generally,
different objects of a class have some difference in the values of the attributes.
Attributes are often referred as class data.
 A set of operations that portray the behavior of the objects of the class. Operations are
also referred as functions or methods.

A class in Python can be defined using the class keyword. Syntax for creating python class is
given below;

class <ClassName>:
<statement1>
<statement2>
.
.
<statementN>

The followings are class members

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.

Example: Instance Attributes


class Student:
schoolName = 'BSU' # class attribute
def __init__(self, name, age): # constructor
self.name = 'Francis' # instance attribute
self.age = 30 # instance attribute
*An instance attribute can be accessed using dot notation: [instance name].[attribute
name], as shown below. *
std = Student()
print(std.name)
print(std.age)
{ instance attribute can also be accessed as}
std.name= ”Francis”

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

You might also like