Python Programming Language A Crash Course To Mast
Python Programming Language A Crash Course To Mast
Python Programming Language A Crash Course To Mast
Gary Elmer
Copyright
All rights reserved. No part of this book may be reproduced or used in any manner without the prior
written permission of the copyright owner, except for the use of brief quotations in a book review.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility
for any errors or omissions that may be made. The publisher makes no warranty, express or implied,
with respect to the material contained herein.
Printed on acid-free paper.
1. Variable
2. Constant
3. Keywords
4. Data types
5. Identifiers
6. Repetition/Loops
7. Decisions/Selections
8. Arrays
PROGRAMS
A program is a set of commands in the form of codes written to instruct a
computer to execute a given task. Codes are embedded in a program so they
are written as the input and processed as instructions to perform a specific
task. An example of program is
Z = X + Y,
The mathematical expression given above is an example of a program
where X, Y and Z are variables. When we instruct the computer to calculate
the value of X and Y, the result which is Z is the output.
DATA TYPES
In python, each dataset given belongs to a category which shows the kind of
tasks a program can be expected to implement on the dataset, this category
is known as the data type. The standard types of data in Python are:
1. Numeric
2. Sequence type
3. Boolean
4. Set
5. Dictionary
NAMING VARIABLES
In one of the previous sections, we defined variables as values that can be
modified in a program. When you change the values of variables in Python,
you need to follow certain guidelines so you do not create a wrong code
that will not deliver the required output. Python has specific variable
naming guidelines:
USING OPERATORS
When writing programs in Python, certain elements are used to execute
tasks on given variables and values to give results. These elements are
represented by symbols known as operators. For example, if we need to
perform subtraction operation on given values, we use the ‘-’ operator to
give the instruction, i.e;
print ( 15 - 11)
There are various categories of operators in Python:
1. Arithmetic operators: they are used to execute mathematical
tasks on numeric values. Examples of arithmetic operators are
addition ( + ); subtraction ( - ); multiplication ( * ); division ( / );
modulus ( % ); exponentiation ( ** ) and floor division ( // ).
2. Assignment operators: these operators are used to assign values
to variables. They assign values of right operand to the left
operand. Their examples are equal to ( = ); add AND ( += );
subtract AND ( -= ); multiply AND ( *= ); divide AND ( /= );
modulus AND ( %= ); exponent AND ( **= ); floor division
AND ( //= ).
3. Comparison operators: they are used to compare two given
values on both sides of the operand and deduce the relationship
that exists between them. The common comparison operators are
equal ( == ); not equal ( != ); greater than ( > ); less than ( < );
greater than or equal to ( >= ); less than or equal to ( <= ).
Another name for comparison operators is relational operators
4. Logical operators are used in combining conditional statements.
‘And’ ( true if both statements are true); ‘or’ (used if one of the
statements are true) and ‘not’ (false if both statements are false)
are all examples of logical operators. They are referred to as
Boolean operators.
5. Membership operators: are used to identify the relationship of a
particular sequence in an object. Operators used to indicate
membership are ‘in’ (true if a sequence with the specified value
is found within an object); ‘not in’ (true if a sequence with the
specified value is not found within an object).
6. Bitwise Operators: are used in comparison of binary numbers.
They work on bits and execute tasks bit by bit. AND ( & ); OR ( |
); XOR ( ^ ); NOT ( ~ ); Zero fill left shift ( << ) and Signed right
shift ( >> ) are examples of bitwise operators used in python.
7. Identity operators: they compare the memory locations of two
different objects. The two identity operators are ‘is’ (true if the
variables on either sides of the operator point to the same object
and false if not); ‘is not’ (false if the variables on either side of
the operator point to the same object and false if not).
There is operator precedence in python. If there are more than one
operations to be performed, one of the operators needs to be evaluated
before others. For example, multiplication has a higher precedence than
addition.
ITERATION
Sometimes, when writing programs in Python, you might need to repeat a
task. When repeating similar tasks, you are bound to make errors so Python
makes this less tasking by having features to aid repetition of tasks without
errors. The execution of a code over and over again is known as iteration .
With iteration, you can repeat the same task a number of times. A program
that utilizes iteration in its codes is referred to as a loop . There are two
types of iteration; definite and indefinite. While carrying out an indefinite
iteration, the number of times the loop has to be repeated is not stated but
with definite iteration, it is stated when the loop starts. In Python, definite
iteration is performed with the for loop while indefinite iteration is
performed with while loop.
When definite iteration loops are used, for is the keyword used to integrate
them into a program in Python. Python implements the collection-based or
iterator based loop which loops a collection of items rather than individual
values. It is the most widely used loop and uses the keyword for each
instead of for . An example of for loop is
for a = 10 to 15
< loop body >
The program above means for every time a is between 10 and 15, the
program should be repeated.
The while loop is used to indicate in-definite iterations where the number
of times the loop has to be iterated is not specified. It is used to iterate a set
of codes with a ‘true’ condition attached to it. When the ‘true’ condition is
no longer met and becomes false, the while loop stops iterating and the
next loop in the program is performed. The next loop which becomes
executed is the else statement which has been programmed to run if the
while loop is broken. In conclusion, the while loop is used when we do not
know the number of times a program has to be executed, if it is known, then
for loop should be used. An example of while loop is
num = 65
while num<81
print ( num )
this program will continue to print 65 until the loop is broken and the
condition of the number being less than 81 is no longer met. It will then
proceed to execute the next program.
CHAPTER TWO
FEATURES OF PYTHON
As a programming language, Python offers many useful and sophisticated
features thereby making it a first choice in the programming industry. It is
versatile as it offers procedural oriented programming as well as object-
oriented programming. Python offers many features to its users, some
significant ones are:
2. Ease of coding
With Python, anyone can learn to code. Although it is a high-level
programming language, it is easy to master and very beginner-friendly
when compared to other programming languages.
3. Extensibility
With Python, programs can be written into other languages like C++
programming language and vice versa.
4. Portability
Python can be used across various OS without having to rewrite the code. If
a program was written on a Mac platform, it can be run on other platforms
like Windows and Linux without changing the code.
5. Object-oriented Language
Object-oriented language is one of the key features of Python. It recognizes
concepts of classes and objects encapsulation which helps in writing
programs with lesser codes and reusable codes.
KEYWORDS/RESERVED WORDS IN
PYTHON
In Python, some keywords have been reserved with specific functions
attached to them so they can’t be used outside these functions and when
naming classes, variables etc. some of these keywords with their functions
are:
● break: break away from a loop.
● and: logical operator
● def: define
● del: delete
● elif: conditional statement if else
● false: comparison operator
● from: import certain parts
● if: conditional statement
● lambda: create anonymous function
These and many more are examples of reserved keywords in Python.
CONCEPT OF LITERALS
Simply put, literals are unprocessed information given in variable or
constant. They are basically constant and do not change throughout a
program’s runtime. In Python, there are five types of literals:
METHODS IN PYTHON
Methods are instructions that can be embedded into an object in order to
execute a task. In other words, they are like action codes called on objects
or classes. They are easy to integrate with a code, once written with the
class or object to work on, output is given without delay. Methods should
not be confused with functions; methods need an object to be able to
perform while objects are not required in functions. As a result of this,
methods can change an object’s behavior and value since they are
associated. There are various built-in methods used in Python namely:
1. Methods for strings: Used when datasets have the same value
but different formats and the data has to be sorted. Methods used
for this situation in strings are lower ( ), upper ( ), strip ( ), split (
) etc.
2. Methods for lists: If a list needs to be modified, then methods
are used. append (arg), remove (arg), count ( ) and clear ( ) are
examples of methods used to modify a list.
3. Methods for dictionaries: Also used to modify the dictionary
data-type. dict.keys ( ), dict.clear ( ) and dict.values ( ) are
methods used when working on the dictionary data-type.
ELEMENTS TO DECLARE
METHODS IN PYTHON
When using methods and functions, there are three basic categories. There
is the built-in category that is already programmed with Python. Next
category is user-defined methods which are created by Python users to
assign certain methods to keywords and lastly anonymous functions. When
declaring user defined methods, certain guidelines should be bore in mind:
1. The def keyword should be used to define the method and its
name.
2. Assign tasks to be executed to the method and provide
descriptions so the method can be clear.
3. Parameters should be added to a method. Enclose them in the
method’s parenthesis and end the line with a colon.
4. Add a return statement to the defined method so an output will
be given. This helps to avoid getting none feedback.
To represent methods and functions, some elements have to be included so
they can perform as desired. These elements are:
● Docstrings: These are used to describe what a function does. It
comes immediately after the function header and is represented with
triple quotes.
● Arguments: Are bits of information sent to a function in its call
time. They come immediately after the function name within the
parenthesis. There are four types of arguments namely keyword
arguments, required arguments, default arguments and variable
number of arguments.
● Parameter: Is a variable written inside the parenthesis in a function’s
definition.
● Recursion: Happens when a function is given the ability to call itself
i.e. data can be looped through or iterated. Care has to be taken to
prevent a situation where the loop keeps going on and eats into the
processor’s memory.
OBJECTS IN PYTHON
One of the most important features of Python is being an object-oriented
programming language; this means almost all entities in Python are objects.
It is the basic block of Python. It is the raw data that is processed to give out
an output. It is a form of dataset with variables and methods embedded in it.
An object is defined by the prototype given by its class. When a real world
problem needs to be solved with Python, the entities like buildings, cars,
interactions between employer and employee, teacher and students and all
forms of entities can be represented as objects with their data inputted to
give out an output. A class is the building block of an object; it contains all
details about the object. An object can also be seen as an instance of a class
i.e. an object belonging only to a particular class. Objects cannot stand
alone; they need a class to define their variables and functions. Usually, the
basic constituents of an object are:
● State: this shows the attributes of a particular object like age, breed,
color etc.
● Behavior: this reflects the methods or functions embedded in an
object e.g. go, come, bark, sleep etc. It also shows the response of an
object to these functions.
● Identity: assigns a name to an object so interactions with other
objects can be possible e.g. Frank, Dog, Car etc.
PACKAGE DEFINITION
Packages in Python are collections of multiple modules. Just as there are
folders and subfolders in computer memories and files are arranged on the
basis of certain criteria so they can be accessed easily, packages perform the
same function in Python. It is used to bundle modules which is an array of
multiple objects with classes and functions. It created a hierarchical
arrangement of the modules to avoid collisions. It is a directory containing
Python files and the package special file _init_py . Modules can be
imported into a package file as long as the special file is present in the
package file. Creating a package is similar to creating folders and
subfolders in a computer. To create a package:
● Create a new folder and name it.
● Create a subfolder in the first folder and give it a desired package
name.
● Create a _init_py file in the subfolder.
● Create or import modules and functions in the package.
# constructor
self.employeeName= name
self.employeeGender= gender
def displayGender(self) :
obj.displayGender()
Output
Name: Frank
Gender: Male
This program shows employee name and gender are public data values.
These values can be accessed from in the program because of this function.
clas s Employee:
_name = None
_gender = None
_role = None
# constructor
de f __init__(self, name, gender, role):
self._name = name
self._gender = gender
self._role = role
de f _displayGenderAndRole (self):
# derived class
clas s Manager(Employee):
# constructor
de f displayDetails(self):
self._displayGenderAndRole ()
# private members
__name = None
__gender = None
__role = None
# constructor
self.__name = name
self.__gender = gender
self.__role = role
de f __displayDetails(self):
# accessing private data members
de f accessPrivateFunction(self):
self.__displayDetails()
# creating object
obj.accessPrivateFunction()
Output
Name: Frank
Gender: Male
Role: Analyst
This program illustrates __name, __gender and __role as private class
members and can only be accessed from within the class. The
accessPrivateFunction ( ) calls for the accessibility of private members of
the class.
An illustration showing a combination of the three forms of access
modifiers is given below
# super class
clas s Parent:
var1 = None
# protected data member
_var2 = None
__var3 = None
# constructor
self.var1 = var1
self._var2 = var2
self.__var3 = var3
de f displayPublicMembers(self):
de f _displayProtectedMembers(self):
de f __displayPrivateMembers(self):
self.__displayPrivateMembers()
# derived class
clas s Child(Parent):
# constructor
de f accessProtectedMembers(self):
obj.displayPublicMembers()
obj.accessProtectedMemebers()
obj.accessPrivateMembers()
#print(obj.__var3)
Output
Public Data Member: Employees
Protected Data Member: Male
Private Data Member: Employees !
The program shows a combination of public, protected and private access
modifiers in a single program.
Summary
Python is a high level programming language with several attractive
features making it desirable for programmers nowadays. The building
blocks which act as the foundation of any program written were identified
along with naming conventions for some of them and guidelines for naming
them have been reviewed in detail in this chapter. These naming
conventions are important for readability and ease of interpretation when
multiple users are involved with a program. It has been established that
variables are memory banks in which data is stored in Python. The
importance of object-oriented programming and its peculiarity in Python
cannot be overemphasized with every entity seen as objects in the
programming language.
CHAPTER THREE
IMPLEMENTING OPERATORS IN
PYTHON
Operators are certain symbols used to execute tasks on given variables and
values to give results when writing programs in Python. They are used to
manipulate values of operands. Without operators, certain tasks can’t be
carried out in Python. When using operators as functions, additional
functions can be merged with the primary function of the operator. This
concept is known as operator overloading. When this happens, it is
observed that the same built in function of an operator performs differently
with objects of different classes. An example is a situation where the
operator + is expected to perform addition functions ordinarily. When the
operator is overloaded, it will be able to merge lists or concatenate two
strings depending on the objects in the classes. When functions are
overloaded in a program, the codes can be reused without having to rewrite
multiple codes with slight variations. It also improves code clarity and
eliminates complexity. However, overloading should not be applied too
much when writing programs to avoid confusion and inability to interpret
codes properly. An example of a program where overloading is used is on
the len() function on Buy class is:
class Buy:
COMPARISON OPERATORS
They are used to compare two given values on both sides of the operand
and deduce the relationship that exists between them. They are also known
as relational operators. When operands are compared with these operators,
the result given will be True or False depending on whether the condition is
attached to the statement. There are six comparison operators used in
Python:
● Less than (<): gives true result if the operand on the left is less than
the operand on the right. If this condition is not met then the result is
false. An example is
4<10
The output is true since 4 is less than 10.
● Greater than (>): gives true result if the operand on the left is greater
than the operand on the right. If this condition is not met then the
result is false. With the example above
4>10
The output is false since 4 is not greater than 10.
● Less than or equal to (<=): gives true result if the operand on the left
is less than or equal to the operand on the right. If this condition is
not met then the result is false.
4 <= 10
Output is true since 4 is less than 10, one of the conditions of the
operator has been fulfilled.
● Greater than or equal to (>=): gives true result if the operand on the
left is greater than or equal to the operand on the right. If this
condition is not met then the result is false.
4>=10
Output is false since 4 is not greater than 10 or equal to 10.
● Equal to (===): gives true result if the operand on the left is equal to
the operand on the right. If this condition is not met then the result is
false.
4===10
Output is false as 4 is not equal to 10.
● Not equal to (!==): gives true result if the operand on the left is not
equal to the operand on the right. If this condition is not met then the
result is false.
4 !== 10
Output is true as 4 is not equal to 10.
Logical Operators
Logical operators are used in combining conditional statements. ‘And’ (
true if both statements are true); ‘or’ (used if one of the statements are true)
and ‘not’ (false if both statements are false) are all examples of logical
operators. They are referred to as Boolean operators.
Identity operators
Identity operators compare the memory locations of two different objects.
The two identity operators are ‘is’ (true if the variables on either sides of
the operator point to the same object and false if not); ‘is not’ (false if the
variables on either side of the operator point to the same object and false if
not).
Membership operators
Membership operators are used to identify the relationship of a particular
sequence in an object. Operators used to indicate membership are ‘in’ (true
if a sequence with the specified value is found within an object); ‘not in’
(true if a sequence with the specified value is not found within an object).
Bitwise operators
Bitwise operators are used in comparison of binary numbers. They work on
bits and execute tasks bit by bit. AND ( & ); OR ( | ); XOR ( ^ ); NOT ( ~ );
Zero fill left shift ( << ) and Signed right shift ( >> ) are examples of
bitwise operators used in python.
OPERATOR PRECEDENCE IN
PYTHON
When using Python, there could be several operators in a program that
needs to be executed. When this happens, there is a rule of precedence
which determines the order in which each of the operators is carried out.
The rule of precedence in Python is listed below with level of precedence in
descending order i.e. from highest to lowest.
● Parentheses ()
● Exponent **
● Bitwise NOT +x, -x,~x
● Multiplication, division, floor division, modulus *, /, //, %
● Addition, subtraction +,-
● Bitwise shift operators <<,>>
● Bitwise AND &
● Bitwise XOR ^
● Bitwise OR |
● Comparison, identity and membership operators ==,!=,>,>=,<,<=,is,
is not, in, not in
● Logical NOT not
● Logical AND and
● Logical OR or
Summary
Operators are an integral part of programming with Python and it has been
examined critically in this chapter. The various types are evaluated along
with the operators distinct to each type, their examples and applications are
also discussed. Overloading of operators is good but should not be over-
exploited to prevent a program from becoming cumbersome. Also, the
guide of operator precedence should be properly followed so the task
assigned to a program will be executed properly to get the desired result.
CHAPTER FOUR
CONDITIONAL AND LOOP
CONSTRUCTS
As discussed earlier, conditions can be introduced into programs to direct
the program to give different outcomes when variations exist in the
conditions outlined. Boolean operators are used to denote True or False
conditions in programs. Comparison and arithmetic operators are applied on
variables which then give outputs as either True or False. So the condition
attached to a certain action determines the action that will be performed,
these programmed actions are known as Conditional constructs or
statements. The loop construct suggests the execution of a code over and
over again. With loops, you can repeat the same task a number of times.
When loop construct is implemented, a sequence of steps keeps getting
executed as long as the condition attached is being met. Once the loop
breaks or the condition is no longer met, the sequence is not followed again
and a new task is executed.
ARRAYS
Although Python does not have an in-built function for arrays, Python Lists
are modified to give arrays. An array can be illustrated as a classroom with
each seat numbered with a value, where each student is seated and can be
easily identified by knowing the number of their seat. Arrays are useful
when large data of similar type needs to be represented by a single variable,
this ability makes it a special variable. Multiple values are held in an array
under a single variable and individual values can be accessed through an
index number. When working with arrays in Python, a NumPy library has
to be imported to be able to use lists as arrays. Since an array is a variable,
its elements can be manipulated and modified as with a list.
ARRAY CREATION
To create an array, the array(data type,value_list) module has to be
imported. This specifies the data type and list of each value.
# Python program to demonstrate creation of array
# importing “array” for array creations
Import array as arr
# creating an array with integer type
A = arr.array(‘i’, [1, 2, 3])
#printing original array
print (“The new created array is : ”, end = “ ”)
for I in range (0, 3):
print (a[],end = “ ” )
print ()
# creating an array with float type
b = arr.array(‘d’, [2.5, 3.2, 3.3])
# printing original array
print (“The new created array is : end = “ ”)
for I in range (0, 3):
print (b [i], end = “ ”)
Output
The new created array is : 1 2 3
The new created array is : 2.5, 3.2, 3.3
Enums
In Python, an enum is used in creating an enumeration of a set of symbolic
members bound to unique constant values. It is a simple data collection type
for representing names, enums names begin with uppercase letters and
values used are singular. To create an enum, the enum module is used. An
enum’s name is displayed using ‘name,’, type() is used to check the enum
type and ‘repr()’ represents the object in the string.
import enum
#using enum class create enumerations
Class Months (enum.Enum)
Jan = 1
Feb = 2
Mar = 3
# print the enum member as a string
print (“The enum member as a string is : “, end=””)
print (Months.Jan)
# print the enum member as a repr
print (“the enum member as a repr is : “,end =””)
print (repr(Months.Feb))
#check type of enum member
print (“The type of enum member is : “,end =””)
print (type(Months.Feb))
#print name of enum member
print (“The name of enum member is : “,end =””)
print (Months.Feb.name)
Output
The enum member as a string is : Months.Jan
The enum member as a repr is :
The type of enum member is :
The name of enum member is : Feb
Strings
A string is a list containing Unicode characters represented with single (‘’)
or double quotes (“”).
Unicode characters are symbols from all languages used in coding. Creating
strings can be likened to assigning values to variables in Python. To assign
a string to a variable, the ‘equal to’ sign is used as displayed below
b = “Hello”
print(b)
To access the elements in a string, square brackets are used
b = “Hello, World!”
print([b1])
Strings can also be looped through with the for function. For example, to
loop through the letters in the word ‘pencil’:
for a in “pencil”:
print(a)
These functions and many others can be performed on strings.
INHERITANCE AND
POLYMORPHISM IN PYTHON
In chapter two, inheritance was briefly discussed with access modifiers.
Inheritance in programming is similar to inheritance in real life as a new
class is created from an existing class which transfers its characteristics to
the new class. However, polymorphism is a concept which displays the
execution of a task in various forms. It gives the object the luxury of
choosing the kind of function to be performed on it. Both concepts are
examined in detail in this section.
Inheritance
A parent can transfer his/her genetic characteristics to their offspring and
the offspring inherits these characteristics even though he/she possesses
their unique characteristics as well. As an object oriented programming
language, inheritance is necessary when writing programs. When a class
inherits the attributes and variables of another class, inheritance can be said
to have occurred. This leads to code reusability within and outside the
program as well as reducing code length. The class from which attributes
are transferred to another can be referred to as the base class while the class
to whom attributes are transferred can be referred to as the child class.
There are five types of inheritance namely:
1. Single inheritance
2. Multi-level inheritance
3. Multiple inheritance
4. Hybrid inheritance
5. Hierarchical inheritance
To create a base class and child class
class Person:
def__init__(self, fname,lname):
self.firstname = fname
self.lastname = lname
def printname (self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
a = Person(“Frank”, “Pen”)
a.printname()
class Employee(Person)
pass
POLYMORPHISM
Breaking down the word, “poly” means many while “morphism” means
form. Therefore, polymorphism is a situation where a function name can be
responsible for executing different tasks. As with inheritance where a child
class inherits attributes from the base class, sometimes the attributes
inherited do not actually fit into the child class so they are modified to fit
and re-implemented, this process is known as method overriding or run-
time polymorphism. Polymorphism provides flexibility of codes and allows
objects to be used by functions without giving space for distinction across
the classes. It allows different object classes to share the same method
name. It is basically applied to functions and used in pattern designing.
Types of polymorphism includes:
class donkey(Animal):
def age(self):
print(“Age of donkey.”)
obj_animal = Animal()
obj_leopard = Leopard()
obj_donkey = Donkey()
obj_animal.type()
obj_animal.age()
obj_leopard.type()
obj_leopard.age()
obj_donkey.type()
obj_donkey.age()
Output
Various types of animals
Age of the animal.
Various types of animals
Age of leopard
Various types of animals
Age of donkey
The error code displayed in the last line of the program shows the types of
errors that occurred in the program. ZeroDivisionError, NameError and
TypeError are found in this program but the string printed as exception type
is the name of the built-in exception that occurred in the program.
To handle exceptions in Python, try and except keywords are used. To
catch exceptions, try block is used while except block handles the
exception. A finally block can also be added so the program it is attached
to is executed without minding where the exception occurs. A simple
program where exception error is handled using try and except blocks is
displayed below:
a = [1, 2, 3]
try:
print “Second element = %d” %([1])
# Throws error since there are only 3 elements in array
print “Fourth element = %d” %([3])
Except IndexError:
print “An error occured”
Output
Second element = 2
An error occurred
In the program above, runtime error occurs when the print “Fourth
element” command was given.
When handling exceptions, the except block can be executed more than
one in a program with several exceptions but at most, only one handler will
be executed. This situation is displayed below:
try :
a=3
if a < 4:
# throws ZeroDivisonError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print “Value of b = “ , b
# note that braces ()are necessary here for multiple exceptions
Except(ZeroDivisionError, NameError):
Print “\nError Occurred and Handled”
Output
Error Occurred and Handled
If the value of (a) is changed to greater than or equal to 4, the output given
will be
Value of b =
Error Occurred and Handled
This is as a result of the NameError that occurs when the value of b needs
to be accessed. For the finally block to be executed, the try block has to be
terminated. Else block is also used when the try block does not result in an
exception. A syntax featuring all these exception handling keywords is:
# Python program to demonstrate exception
try:
a = 7//0 # raises divide by zero exception
print (a)
# handles zerodovision exception
except ZeroDivisionError:
print(“Can’t divide by zero”)
else:
# execute if no exception
finally:
# this block is always executed
# regardless of exception generation
print(‘This is always executed’)
Output
Can’t divide by zero
This is always executed
This sample program displays the exception handling keywords discussed
in action
EXCEPTION DEFINITION
As mentioned earlier, exceptions are errors that arise in programs even
though the codes are syntactically correct. Exceptions are unavoidable but
when handled properly, they do not lead to termination of programs. They
are triggered by actions that Python cannot execute or perform. Examples
of standard exceptions that are raised in Python include:
● Exception: the basic form of exception.
● StopIteration: this is triggered when the next()function of an iterator
has no object to perform on.
● ArithmeticError: class of errors with roots from numeric operations.
● StandardError: all types of exceptions except StopIteration and
SystemExit.
● ZeroDivisionError: occurs when numbers are divided by zero.
● IndexError: oc)curs when a sequence index number for objects is not
found.
● NameError: occurs when the namespace is empty.
● SyntaxError: occurs as a result of error in Python syntax.
● SystemError: occurs when the Python interpreter fails to exit a
program due to an internal fault.
● RuntimeError: occurs when the error code in a program cannot be
attributed to any error category.
These and many others are built-in exceptions in Python.
ASSERTION IMPLEMENTATION
The assertion function is raised from the exception. It is a concept that
allows a programmer to attach a condition to a code. A True condition
implies execution of the next code while False stops the program from
running. The assert statement is used to execute assertions in a program.
When the condition comes False, AssertionError Exception is implemented.
So when a program has passed the testing stage, assertion can be
implemented as a sanity check. Assertions are implemented when a
function is called to ascertain the input validity and after the function to
check for the output. This establishes assertion as a debugging aid utilized
in program self-checks, however, it cannot be used in handling run-time
errors.
Output
Enter a number: -19
Only positive numbers accepted.
As a result of the except block in the program above, this program will not
stop. The except block will pass the assert statement as an exception
argument.
Overall/general principles of Testing and Writing Programs
After writing a program in Python, it is subjected to tests of various types to
determine its usability. These tests form a crucial part of activities done
after writing a program. However, there are certain guidelines to performing
testing on programs. They are called principles and are briefly explained
below:
PROGRAMMING BEING
STRUCTURED
In program writing, there are three main structures which serve as building
blocks in programming. They are:
● Sequence: is a series of events which are completed in a specific
order. An action leads to a next action is a predetermined order in
sequence structure. The actions are completed in the set order without
skipping any when the sequence is set.
● Selection: is a bit different from sequence as a condition is attached
to the program. The outcome of the condition determines the next
action in the program.
● Loop: keeps repeating a code until the attached condition is no more
fulfilled. The type of loop in the program determines when it stops
repeating.
Output:
error: expected ‘;’ before ‘}’ token
The compiler error in this program is as a result of not adding parentheses
before the closing brace.
Another example of compiler error arising as from syntax error is
a = int(input(‘Enter a number:’))
if a%4==0
print(‘You have entered an even number.’)
else:
print(‘You have entered an odd number.’)
Output
C: Python34Scripts>python error .py
File “error .py”, line 3
If a%4==0
^
SyntaxError: invalid syntax
The program above gave an error due to the missing colon (:) at the end of
the if statement. This hinders the program from running.
RUNTIME ERRORS
These are errors encountered during a program’s runtime after code
compilation. They are hard to detect because the program does not
distinguish the line causing the error. they can be found by proofreading the
code line by line or testing the program with a debugger. When runtime
error occurs, the program misbehaves, displays an exception dialog box,
gives a wrong output, freezes the application or shutdown totally. They are
caused by variable name misspelling and other errors of commission.
Inputting wrong information into the application or computer hardware
problem can also raise runtime error. In essence, error of commission and
error of omission causes runtime error. Common examples of runtime error
are division of numbers by zero, deducing square roots of negative integers
etc.
DEBUGGING IN PROGRAMS
After writing a program, debugging is done to detect and deal with the
various errors discussed earlier. So, a debugger serves as a tool used to
search through the nooks and crannies of a program, the variables, source
codes and every core area of the program for defects, errors and every other
problem in a program and also solve them. It acts by performing all actions
in a program, executing the tasks line by line and repeating these actions to
detect abnormalities and bugs in the program through the development
process.
There is a built-in debugging tool in Python called pdb . It comes with the
Python program and has all functions needed to detect errors and solve
them. Its features can also be extended using ipdb from IPython. To use
pdb , it has to be called into the code to be debugged, i.e.
Import pdb; pdb.set_trace()
Some programmers also use the print function to show a program’s
behavior and spot bugs rather than default debuggers. To stop debugging,
the quit function is called by pressing “q” followed by ENTER key.
Summary
Various types of errors that might arise during code writing and execution
are discussed in this chapter. Exception handling is done with the try,
except, else and finally functions.
Assertions are implemented when a function is called to ascertain the input
validity and after the function for check for the output, it is raised from
exception. In program testing, pesticide paradox should be avoided and
also, testing should be program-context dependent. These and other
principles of testing are necessary for detecting defects. Code writing
principles like keeping it simple, resilient and of good standard needs to be
followed to turn out great codes. Errors should be detected early in
programs to avoid rewriting and save time and resources. Each program
should be developed towards solving a specific program so proper planning
should be implemented.
About the Author
Gary Elmer is a writer dedicated to the world of technology and
programming software innovations. He has written a number of books that
proved to be very helpful in breaking down the intricacies of the world of
technology to readers. This guide to Python programming language is
another entry in the series and has gathered numerous positive reviews