0% found this document useful (0 votes)
69 views54 pages

Computer Programming Basics and Concepts

The document provides an overview of computer programming, detailing its definition, the program development life cycle, and characteristics of good programs. It also discusses programming languages, methodologies, and the principles of object-oriented programming (OOP), including encapsulation, inheritance, and polymorphism. Additionally, it highlights the advantages of high-level languages and the importance of OOP in software development.

Uploaded by

wachukudavid07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views54 pages

Computer Programming Basics and Concepts

The document provides an overview of computer programming, detailing its definition, the program development life cycle, and characteristics of good programs. It also discusses programming languages, methodologies, and the principles of object-oriented programming (OOP), including encapsulation, inheritance, and polymorphism. Additionally, it highlights the advantages of high-level languages and the importance of OOP in software development.

Uploaded by

wachukudavid07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CARITAS UNIVERSITY, ENUGU

COMPUTER SCIENCE DEPARTMENT

COURSE CODE: COS 201

COURSE TITLE: COMPUTER PROGRAMMING I

1|Page
CHAPTER ONE
COMPUTER PROGRAMING
1.1 Overview of Computer Programming
Computer programming is the art of defining a problem and expressing the steps to solve the
problem as instructions in any chosen programming language of your choice for a computer to
follow. Programming is the process of giving machines a set of instructions that describe how a
program should be carried out. Programmers will spend their whole careers learning a variety of
programming languages and tools so they can effectively build computer programs. Programmers
use a code editor or an integrated development environment (IDE) to write source code. The source
code needs to be converted into machine language so the computer can understand the instructions
and execute the program. The process of converting the source code into machine language is
known as compiling. Examples of compiled languages are C++, C, Java, etc. Other languages do
not use a compiler. Instead, these languages use an interpreter that will read and execute the source
code. Examples of interpreted languages are JavaScript and PHP. Once the code is executed, the
computer program can run. The different types of computer programs include word processors,
database systems, video games, and websites. Through programming language, we instruct the
computer to carry out some processes or tasks. Therefore, computer programming language is
designed in order to communicate ideas about algorithms between human beings and computers.
While computer program is a sequence of instructions given to the computer to perform a particular
task.
Examples of popular programming
• Python
• JavaScript
• C/C++
• Java
• C#
• Ruby
• PHP
• QBasic
• Visual Basic

2|Page
• MATLAB
• PASCAL etc.
Computer programming involves two steps:
Problem definition and logical steps to solve the problem: problem definition and analysis are
performed using different tools such as algorithms, pseudocode, structured charts, and flowcharts.
Communicating the logical steps to the computer. To communicate the logical steps to the
computer, various programming languages are utilized. Some of these programming languages are
as outlined earlier.
1.2 Program development life cycle
A computer program is a sequence of instructions given to the computer to perform a certain task.
The program development life cycle is a step-by-step plan for developing efficient software or
programs. The step-by-step plan includes:
(i). Problem analysis: this enables you, the programmer, to understand the problem and the likely
outputs the system will produce. In addition, it involves input definition (data), and the relationship
between input and outputs.
(ii) Program design: the phase involves planning the solution to the problem using different tools
such as algorithms, flowcharts, pseudocode, and a structured chart. These tools assist programmers
in breaking the problem into a sequence of small tasks that the computer can program.
(iii). Coding: translate the algorithm into a programming language
(iv). Testing and Debugging: the process of locating and removing errors in a computer program.
Testing is the process of finding errors in the program, while debugging is the process of correcting
errors found in the program. Errors may occur in a program due to typing mistakes, logical flaws
in the algorithm, and incorrect usage of programming language rules.
(v). Documentation: Organize all the materials that describe the program
1.3 Characteristics of a good program
i. Integrity or accuracy: Refers to the accuracy of the computation don in the program.
ii. Clarity: Is the overall readability of the program code with emphasis on its underlying
logic.
iii. Simplicity: the program should be simple and consistent with overall program
objectives
iv. Efficiency: relative to program speed of execution and memory utilization

3|Page
v. Modularity: Process of breaking a program into identifiable subtasks. Each subtask is
implemented separately and then combined to form a complete program code.
vi. Generality: the ability of the program to be applied to different situations or data
elements instead of a specific situation or data element. This is achieved through the
use of variable arguments instead of constant values.
1.4 Reasons for programming or learning programming languages
• Help you to understand the computer;
• Increase your confidence level at solving complex problems;
• Enhances thinking ability;
• Improves your communication and collaborative skills;
• Increases your chances of getting a job.
1.5 Levels of Programming Language
a. Machine language: a low-level language that consists of 0's and 1's (binary). High-level
languages are compiled into machine code so the code can be executed by the computer.
However, machine language is tedious and difficult to write. They are not user-friendly as
users are required to remember a list of codes, numbers, and operations. Moreover,
debugging the code is difficult
b. Assembly language: a low-level language that is compiled by an assembler. Assemblers
translate human code to machine code. Assembly language uses symbolic code
(Mnemonic) such as ADD for addition, SUB for subtraction, MUL for multiplication, and
reference memory addresses of the computer. A translator is used to convert assembly
language into low-level machine language. Therefore, a translator is an assembler program
that takes assembly language and converts it into machine language. However, assembly
language is repetitive, tedious, and error-prone.
c. High-level language: these are programming languages that use near-human language, and
they are independent of the computer executing the program. High-level languages deal
with variables, arrays, object-oriented approach, complex arithmetic, Boolean expressions,
classes, block functions, procedures, etc. Examples of high-level languages are JAVA,
C++, C#, Python, COBOL, PASCAL, C, Kotlin, Visual Basic, and QBasic, etc.
1.6 Advantages of High-level languages

4|Page
• User friendly and easy to learn and write compare to machine language and assembly
language;
• It is very portable and can be used in any computer;
• Efficient and saves time and effort compare to other programming languages
mentioned earlier;
• Easy to debug code written in high level language.
1.7 Features of most programming languages
• Must have synthetic rules for forming variables, statement etc.
• Have vocabulary consist of letters of the alphabet
• Must have language structure that consist of statement, keywords, and expression
• May require a translator to be understood by the computer.
1.8 Programming Methodologies
• Procedural programming: execute statement in consistent sequence or series of steps.
These series of steps are used to perform calculation, retrieve input or produce output.
Examples include COBOL, QBasic, FORTRAN, PASCAL, C etc.
• Object oriented Programming: this works with the idea of building programs around
collections of objects. This is a collection of objects that interact with each other through
message passing. It uses object modelling, classification and inheritance to develop
program blocks. Examples of object-oriented programming are C++, JAVA, Python,
Kotlin, JavaScript, [Link] etc.
• Functional programming: is functional program is a collection of mathematical functions
consisting of input (domain) and result (range). It uses functional composition and
recursive approaches to enable interaction and composition of functions. Examples are
LISP, Scheme, and Haskell.
• Declarative (logic) programming: this is a collection of logical declaration about what
outcome a function should accomplish rather than how that outcome should be performed.
Logical programming provides a natural vehicle for expressing non-deterministic values
and extensively used in artificial intelligence development. Example is Prolog
programming language.
• Event-driven programming: an event driven programming is a continuous loop that
responds to an event that are generated in an unpredicted order. These events originate

5|Page
from user actions on the screen (mouse click or key stroke) or from other sources such as
reading from sensors on a robot. Examples of event driven are JAVA and VB
• Concurrent Programming: this is a collection of cooperating processes sharing information
from time to time asynchronously. Examples are FORTRAN, Linda.
• Scripting language: these languages often don't need to be compiled but rather interpreted.
Interpreted means an interpreter will read and execute the code instead of being compiled
into machine code. Examples are PHP and JavaScript.

6|Page
CHAPTER TWO
OBJECT ORIENTED PROGRAMMING
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions and logic. An object can be understood as a real-world
entity—such as a student, a car, a bank account, or a textbook, represented in code. OOP allows a
programmer to model these real-world entities by combining data (attributes) and the behaviors
that operate on that data (methods).
The primary goal of OOP is to make programs more modular, reusable, organized, and easier to
maintain. As applications grow in size, using only functions and global data becomes difficult to
manage. OOP offers a structured way of grouping related data and functions together into logical
units. These goals are explained below:
a. Robustness:
Every good programmer wants to produce correct software, which means that a program produces
the correct output for all anticipated inputs within its application. In addition, we want the software
to be robust, meaning it can handle unexpected inputs that are not explicitly defined for its
application. The software code should be able to handle unexpected errors, produce correct
solutions, and expand to handle more data elements.
b. Adaptability:
Modern software projects, such as word processors, web browsers, and Internet Search engines,
typically involve large programs that are expected to last for many years. Therefore, software needs
to evolve in response to changing conditions in its environment. The program should adapt to
changes or an increase in CPU, network speed, or additional software functionalities.
c. Reusability:
The goal is to maximize code reuse through object-oriented principles such as inheritance.
Inheritance allows new classes to inherit properties and behaviors from existing ones, reducing
redundancy and accelerating development. Classes and objects can be designed as self-contained
units that can be easily integrated into various parts of a program or even different projects.
d. Maintainability
Object-oriented approach organizes code into well-defined, independent objects, thereby
simplifying the process of identifying and fixing bugs, as well as introducing new features.

7|Page
Therefore, changes within one object are less likely to impact other parts of the system, making
maintenance more manageable.
e. Abstraction
This focuses on preparing essential information while hiding complex implementation details. This
simplifies the user’s interaction with objects and reduces cognitive load for the developers.
f. Security:
Encapsulation and data hiding principles in object-oriented programming helps to protect data
integrity by restricting direct access to an object’s internal state, thereby enhancing program
security.
g. Modularity and Organization
Object-oriented programming encourages breaking of complex system into smaller, manageable
modules (objects). Each object encapsulates its own data and the functions that operate on that
data, leading to a more structured and understandable codebase.
Python is an object-oriented language, meaning it naturally supports OOP, and even built-in types
such as strings, lists, and dictionaries are implemented as objects under the hood.

Fundamental Principles of Object-Oriented Programming


Four fundamental principles of OOP are encapsulation, abstraction, inheritance, and
polymorphism. These are explained below:
1. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In Encapsulation, the variables or data of a class
are hidden from any other class and can be accessed only through any member function of their
class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.

8|Page
2. Data Abstraction:
Data abstraction is one of the most essential features of object-oriented programming. Data
abstraction refers to providing only essential information about the data to the outside world,
hiding the background details or implementation. Consider a real-life example of a man driving a
car. The man only knows that pressing the accelerator will increase the speed of the car or applying
the brakes will stop the car, but he does not know how pressing the accelerator increases the speed,
or the inner mechanism of the car, or the implementation of the accelerator, brakes, etc in the car.
This is what abstraction is.
3. Inheritance
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a class
to derive properties and characteristics from another class is called Inheritance. When we write a
class, we inherit properties from other classes. So when we create a class, we do not need to write
all the properties and functions again and again, as these can be inherited from another class that
possesses it. Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.

9|Page
4. Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For example,
A person at the same time can have different characteristics. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behavior in different
situations. This is called polymorphism.

5. Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime.
Dynamic binding means that the code associated with a given procedure call is not known until
the time of the call at run time. Dynamic Method Binding One of the main advantages of
inheritance is that some derived class D has all the members of its base class B. Once D is not
hiding any of the public members of B, then an object of D can represent B in any context where
a B could be used. This feature is known as subtype polymorphism.

10 | P a g e
6. Message Passing
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and, therefore, will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information to be
sent.
7. Syntax
This is the set of rules that define how words and punctuation are organized in a programming
language.
8. Coupling
this is the degree to which software elements are connected to each other. For instance, if a class
has its attributes change, then any other coupled class also changes.
9. Association
This is the connection between one or more classes. Association can be one-to-one, or many-to-
many to one-to-many, one-to-many, or many-to-one.

Examples of Object-oriented programming languages


For example, popular pure OOP languages include the following:
• Simula
• Ruby.
• Scala.
• JADE.
• Emerald.
Programming languages designed primarily for OOP include the following:
• Java.
• Python.
• C++.
Other programming languages that pair with OOP include the following:
• Visual Basic .NET.
• PHP.

11 | P a g e
• JavaScript.
The building blocks of object-oriented programming in Python
The building blocks of object-oriented programming in Python are classes, objects, attributes, and
methods. These building blocks and fundamental principles are explained below.
A. Class
A class is a user-defined data type. It consists of data members and member functions, which can
be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.
A class in Python is a blueprint or template for creating objects. It defines the structure that the
objects will have, including:
• Attributes (variables that store data about the object), and
• Methods (functions that define the behavior of the object).
You can think of a class like the architectural drawing of a house. It specifies what the house
should look like, how many rooms it should have, and where the windows and doors will be. This
blueprint is not a house by itself, but builders can use it to create many houses.
In Python, a class is defined using the class keyword.
B. Object
t is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object is
an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated. An object has an identity, state, and behavior. Each
object contains data and code to manipulate the data. Objects can interact without having to know
details of each other’s data or code, it is sufficient to know the type of message accepted and type
of response returned by the objects.
An object is an instance of a class. When the class blueprint is used to create something in memory,
that “something” is an object.
For example, if Student is a class, then:
• s1 = Student ("James", 20) might represent the first student object,
• s2 = Student ("Ada", 19) represents another student object.
Even though both s1 and s2 are created from the same class, they hold different data. Each object
has its own attributes and can perform actions through its methods.
Relationship Between Classes and Objects

12 | P a g e
• A class is abstract (a plan); an object is concrete (a usable instance).
• A class defines properties; an object stores actual values.
• A class defines behaviors; an object executes those behaviors.
C. Attributes
Attributes are variables stored inside an object. They describe properties or characteristics of the
object.
There are two major types:
1. Instance attributes – unique to each object.
Example: A student’s name or age.
2. Class attributes – shared by all objects of the class.
Example: The school’s name.
In Python, attributes are usually defined inside the __init__ method for instance attributes, and
directly under the class indentation for class attributes.
D. Methods
Methods are functions defined inside a class. They describe the behaviors or actions that the object
can perform.
Methods always take at least one parameter, usually called self.
• self refers to the specific object calling the method.
• Through self, Python can access or modify an object’s attributes.
Methods allow objects to interact with their data, perform computations, update values, or produce
output.
For example, a method in a student class might calculate a student’s average score or print their
full details.

Simple Class Example: The Student Class


To illustrate these concepts, consider a simple example: modeling a student in Python using a class.
Below is a breakdown in prose, followed by the code example.
The Purpose of the Student Class
The class represents students in a school. Each student object will have:
• Attributes such as name, age, and department.
• Methods such as introducing themselves or updating their department.

13 | P a g e
Using a class allows us to create many student objects with different details, without rewriting
code for each student.
Understanding the Components
1. The class definition:
Using the keyword class Student, we define a new type called Student.
2. The __init__ method:
This is a special method called automatically whenever a new object is created.
It initializes (sets up) instance attributes.
3. Instance attributes:
Inside __init__, we assign values to attributes like [Link], [Link], etc.
4. Methods:
These define what a student object can do, such as displaying their information.
Python Example with explanation
class Student:
# Class attribute shared among all students
school = "Veritas University"

# Constructor: initializes each new student object


def __init__(self, name, age, department):
[Link] = name # instance attribute
[Link] = age # instance attribute
[Link] = department # instance attribute

# Method that describes what the student can do


def introduce(self):
return f"My name is {[Link]}. I am {[Link]} years old and I study {[Link]}."

# Method to update department


def change_department(self, new_dept):

14 | P a g e
[Link] = new_dept
return f"{[Link]}'s department has been changed to {new_dept}."

Explanation of the Code in Prose

The student class begins by defining a class attribute called school, which is shared by all instances
of the class. This means all students attend the same school.

The __init__ method serves as the constructor. It runs automatically whenever a new student object
is created and assigns the name, age, and department provided by the user to the object’s instance
attributes.

The introduction method returns a sentence describing the student. Because it uses [Link],
[Link], and [Link], the output will be specific to each object that calls the method.

The change_department method allows the program to modify the student’s department later if
needed. It updates the department attribute and returns a confirmation message.

Creating Objects from the Student Class


When the class is defined, we can create individual student objects like so:
student1 = Student ("James", 20, "Computer Science")
student2 = Student ("Ada", 19, "Mass Communication")
Each object now holds its own data. Although student1 and student2 share the same class
definition, they store different values.
Using Methods
print([Link]())
print([Link]())
student2.change_department("Software Engineering")
print([Link]())
Each object calls the same methods, but produces different outputs because its attributes differ.
Importance of Object-oriented programming
i. To make the development and maintenance of projects more effortless.
ii. To provide the feature of data hiding that is good for security concerns.
iii. We can solve real-world problems if we use object-oriented programming.
iv. It ensures code reusability.
v. It lets us write generic code, which will work with a range of data, so we don't have to write
basic stuff over and over again.

15 | P a g e
CHAPTER THREE
INTRODUCTION TO PYTHON PROGRAMMING

Python Programming
Python is a widely used general-purpose, high-level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by the Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and included new features.
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our
programs. There are certain online interpreters like [Link]
[Link] or [Link] can be used to start Python without installing an
interpreter.
Windows: There are many interpreters available freely to run Python scripts, like IDLE (Integrated
Development Environment), which is installed when you install the Python software from
[Link]
2) Writing the first program:
# Script Begins
Statement1
Statement2
Statement3
# Script Ends

16 | P a g e
Differences between scripting language and programming language:
S/N Scripting Language Programming language
1 A programming language that supports scripts: A formal language, which
programs written for a special run-time environment comprises a set of instructions
that automate the execution of tasks used to produce various kinds
of output
2 Execution speed is slow Compiler-based languages are
executed much faster, while
interpreter-based languages
are executed more slowly
3 Can be divided into client-side scripting languages and Can be divided into high-
server-side scripting languages level, low-level languages, or
compiler-based or interpreter-
based languages
4 Easier to learn Not as easy to learn
5 Examples of scripting languages are JavaScript, Perl, Examples include C, C++, and
PHP, Python, and Ruby assembly language
5 Mostly used for web development Used to develop various
applications such as desktop,
web, mobile, etc.

Reasons for Using Python


1. Python is object-oriented
Structure supports such concepts as polymorphism, operator overloading, and multiple
inheritance.
2. Indentation
Indentation is one of the greatest features in Python
3. It’s free (open source)
Downloading and installing Python is free and easy
4. It’s Powerful
Dynamic typing

17 | P a g e
Built-in types and tools
Library utilities
Third-party utilities (e.g., Numeric, NumPy, SciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compatible Python interpreter installed, python
Programs will run in the same manner, irrespective of platform.
6. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called byte code, which the
interpreter then reads.
This gives python the development speed of an interpreter without the performance loss inherent
in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by the Python interpreter
8. Interactive Programming Language
Users can interact with the Python interpreter directly to write programs
9. Straightforward syntax
The formation of Python syntax is straightforward, which also makes it popular.

Weaknesses of the Python Programming Language


1. Slow Speed
We discussed above that Python is an interpreted and dynamically-typed language. The line-by-
line execution of code often leads to slow execution.
The dynamic nature of Python is also responsible for the slow speed of Python because it has to
do extra work while executing code. So, Python is not used for purposes where speed is an
important aspect of the project.
2. Not Memory Efficient

18 | P a g e
To provide simplicity to the developer, Python has to do a little tradeoff. The Python programming
language uses a large amount of memory. This can be a disadvantage while building applications
when we prefer memory optimization.
3. Weak in Mobile Computing
Python is generally used in server-side programming. We don’t get to see Python on the client-
side or mobile applications because of the following reasons. Python is not memory efficient and
it has slow processing power as compared to other languages.
4. Database Access
Programming in Python is easy and stress-free. But when we are interacting with the database, it
lags behind.
Python’s database access layer is primitive and underdeveloped in comparison to popular
technologies like JDBC and ODBC.
Huge enterprises need smooth interaction of complex legacy data, and Python is thus rarely used
in enterprises.
5. Runtime Errors
As we know, Python is a dynamically typed language so the data type of a variable can change
anytime. A variable containing an integer number may hold a string in the future, which can lead
to Runtime Errors. Therefore, Python programmers need to perform thorough testing of the
applications.
Applications of the Python programming language
1. Web Development
Python is used for web development and internet applications. Web frameworks
like Django and Flask are of the most popular frameworks. They allow you to write server-side
code in Python.
With a framework, it becomes easier to build backend logic like mapping
different URLs to Python code, dealing with databases, and generating HTML files to view on the
user’s device.
The standard library of Python supports many internet protocols, like:
• HTML
• JSON and XML
• Email processing

19 | P a g e
• FTP and IMAP
• Socket interface.
2. Desktop GUI Applications
You can build desktop applications along with their GUI all in Python.
Python has a simple syntax, modular architecture, and a rich set of tools that can work on various
operating systems. This is the reason why it is suitable for desktop applications.
The platform-independent GUI toolkits that you can use are:
• wxWidgets
• Tkinter
• Qt
• Gtk+
• FLTK
• Kivy
• OpenGL
3. Scientific and Numeric Calculations
A lot of scientists, researchers, programmers, and statisticians use Python for scientific and
numerical calculations.
Python’s simplicity and ability to handle operations with large numbers make it pretty useful in
scientific calculations. There are ample libraries available for Scientific and numeric calculations.
Some of these are:
• SciPy
• Pandas
• IPython
• Numpy
4. Data Science
Data science is one of the hottest fields where Python is deeply involved in the roots.
Python is used to process large amounts of data, clean the data, build machine learning models,
and visualize data.
Some of the important libraries for data science are:
• Numpy
• Pandas

20 | P a g e
• Scikit-learn
• TensorFlow
• Keras
• Pytorch
• Matplotlib

5. Software Development
In software development, Python is mostly used as a support language for building
control and management, testing and automating the workflow.
• SCons – build-control.
• Buildbot and Apache Gump – automation and continuous compilation and testing.
• Roundup or Trac – project management and bug-tracking.
• Tools like Selenium can be used with Python for testing web applications.
6. Education
Python is the most preferred language for beginners and for teaching purposes. It is a good choice
to learn about programming and computer science concepts.
Python forms custom applications without writing additional code.
7. Business Applications
Python has fantastic features like special libraries, scalability, extensibility, and simplicity. Larger
applications can be easily customized using Python.
A popular website, Reddit, which was originally written in Common Lisp was rewritten with
Python in 2005. YouTube also uses Python for some of its functionalities.
Python is a great choice for developing ERP and E-commerce systems.
• Tryton – A three-tier, high-level general-purpose application platform.
• Odoo – It’s an all-rounder management software with a range of business applications. With
that, it forms a complete suite of enterprise-management applications in effect.
8. Games and 3D Graphics
This is an interesting part for everyone, making games is very exciting as you can create anything
with your imagination. Python has some amazing libraries, some of which
are PyGame and PyOpenGL. You can build wonderful games with these libraries. You can create
3D graphics with Python, OpenGL, and Blender 3d API.

21 | P a g e
If you love game development, then you should check out PyWeek, which hosts interesting
gaming contests.
9. Network Programming
Python is also used in making connections between client and server, socket programming,
and network programming.
It supports lower-level network programming.
• Twisted Python – Framework for asynchronous network programming.
• Easy-to-use socket interface for socket programming.
10. Database Access
After all these possibilities, how can Python fall behind in connectivity with databases?
Python is also used in server-side programming, where it connects to SQL or NoSQL databases
and performs database operations.
Some of the libraries for working with databases are:
• PyMySQL – to work with MySQL database.
• PyMongo – to work with the MongoDB NoSQL database.

Python Programming Languages Installation


There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment, which is installed when you install the Python software from
[Link] The installation process is shown in Figure 1.
Steps to be followed and remembered:
Step 1: Select the Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)

22 | P a g e
Figure 1: Installation of Python

Working with Python


Python Code Execution:
Python’s traditional runtime execution model: Source code you type is translated to byte code,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.

Figure 2: Source code extension is .py while Byte code extension is .pyc (Compiled Python code)
There are two modes for using the Python interpreter:
• Interactive Mode
• Script Mode
Running Python in interactive mode
Without passing a Python script file to the interpreter, directly execute code in the Python prompt.

23 | P a g e
Once you’re inside the Python interpreter, you can start.
>>> print("hello world")
hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
5

Figure 3: Starting Python development environment for interactive mode


The chevron at the beginning of the 1st line, i.e., the symbol >>>, is a prompt the Python interpreter
uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.

Running Python in script mode:


Alternatively, programmers can store Python script source code in a file with the .py extension and
use the interpreter to execute the contents of the file. To execute the script by the interpreter, you
have to tell the interpreter the name of the file. For example, if you have a script name [Link]
and you're working on UNIX, to run the script you have to type:

python [Link]

24 | P a g e
Working with the interactive mode is better when Python programmers deal with small pieces of
code as you can type and execute them immediately, but when the code is more than 2-4 lines,
using the script for coding can help to modify and use the code in the future.

Figure 4: script mode in Python

Python Character Set


Python statements, keywords, or reserved words are formed from a set of characters. These
characters are 26 English alphabet (Upper case and lower case) letters A to Z or a to z, ten digits
0 to 9, underscore, etc.
Operators in Python
Operators are symbols or characters for arithmetic and comparison operations. It specifies what
operations to perform on operands or variables. Operators in the Python programming language
include arithmetic operators, comparison operators, logical operators, bitwise operators,
assignment operators, identity operators, and membership operators. These operators are explained
below:
Arithmetic operators: these are used for arithmetic operations such as addition, subtraction,
multiplication, division, and exponentiation. Arithmetic operators are shown in Table 1 below
Table 1: Arithmetic operators
Operators Meaning Functions Examples
() Bracket Grouping x*(y+z)
+ Addition Add two numbers x+y
- Subtraction Subtract two or more operands x-y
* Multiplication Multiply two or more operands x*y
/ Division Division (float): divides the first x/y
operand by the second
// Integer Division Divides the first number by the second x//y

25 | P a g e
% Modulus It divides two numbers and return only 5mod2 = 1
the remainder 4mod 2 = 0
8mod 4 = 0
** Exponentiation Raises to the power of another number 3**2 = 9
4**3 = 64

Comparison Operators: These are used for comparisons among operands or variables and other
types of information in a program. The values returned are either true or false. The relations or
comparison operators are shown in Table 2 below
Table 2: Comparison operator
Operators Description Examples (x = 10, y
= 5)
< It returns true if the right operand is greater than the left x < y = False
operand
<= It will return true if the right operand is greater than or equal x<= y = False
to the left operand.

> It will return true if the left operand is greater than the right x > y = True
operand.

>= It will return true if the left operand is greater than or equal x >= y = True
to the right operand.

== It will return true if both operands are equal. x = y = False

!= Not equal to –True if operands are not equal x!=y

Logical Operator: These are used to perform logical operations or comparison of two or more
operands to result to Boolean values (true or false). Table 3 below shows the logical operators in
Python programming language.
Table 3: Logical operators in Python
Operators Description Examples (x = True or 1, y =
False or 0)

26 | P a g e
AND It will return true if both operands are true (1) x AND y = True, x AND y =
False
OR It will return true if any one operand becomes a x OR y = True, x Or y = False
non-zero value
NOT It will return the reverse of a logical state of Not x
which means if both operands are true, it will
return false.

Bitwise Operator: acts on bits and performs the bit-by-bit operations. These are used to operate on
binary numbers. Examples of bitwise operators are shown in Table 4.
Table 4: Bitwise operators
Operators Description Examples(x=10, b=4)
& Bitwise AND x&y = 0
| Bitwise OR x|y = 14
~ Bitwise NOT ~x = -11
^ Bitwise XOR x^y = 14
>> Bitwise right shift x>>2 = 2
<< Bitwise left shift x<< 2 = 40

Assignment Operators: This is used to assign new values to operands. Typical assignment
operators and examples are shown in Table 5 below.
Table 5: Assignment operators
Operators Description Examples x= 10, y = 2,
Assign value of right side of expression to left
= side operand x=y+z
Add AND: Add right-side operand with left side x+=y x=x+y; x = 10+ 2 =
+= operand and then assign to left operand 12
Subtract AND: Subtract right operand from left
-= operand and then assign to left operand x-=y x=x-y; 10-2= 8

27 | P a g e
Multiply AND: Multiply right operand with left
*= operand and then assign to left operand x*=y x=x*y 10 * 2 = 20
Divide AND: Divide the left operand by the right
/= operand and then assign it to the left operand x/=y x=x/y; 10/2 = 5
Modulus AND: Takes modulus using left and
right operands and assigns the result to the left
%= operand x%=y x=x%y; 10%2 = 0
Divide(floor) AND: Divide the left operand by
the right operand and then assign the value(floor)
//= to the left operand x//=y x=x//y; 10//2 = 5
Exponent AND: Calculate the exponent(raise
power) value using operands and assign the value x**=y x=x**y; 10**2 =
**= to the left operand 100
x&=y x=x&y; x = 10 =
Performs Bitwise AND on operands and assigns 1010; y = 0010; x 0010, x = 2
&= the value to the left operand in base 10
Performs Bitwise OR on operands and assigns x|=y x=x|y; x = 1010; x =
|= the value to the left operand 10 in base 10
x^=y x=x^y; x =
Performs Bitwise xOR on operands and assigns 1010^0010; x = 1000; x = 8
^= the value to the left operand in base 10.
x>>=y x=x>>y; x = 1010,
y= 0010; x = 00001010>>; x
Performs a Bit-wise right shift on the operands
= 0000 0101; x = 5 in base
>>= and assigns the value to the left operand 10
x <<=y x= x<< y; x =
Performs a Bit-wise left shift on operands and
1010; y = 2; x<<2; x = 0001
<<= assigns the value to the left operand 0100; = 20 in base 10

Identity operators are used to check if two values are located on the same part of the memory.
Two equal variables do not imply that they are identical. Identity operators are shown in Table
6.

28 | P a g e
Table 6: Identity Operators
Operator Description Examples (n x = 10; y = 20;
z=x
Is True if the operands are identical x Is z is True
Is Not True if the operands are not identical x Is Not y is True

Membership Operators: used to test whether a value or variable is in a sequence. Membership


operators are shown in Table 7 below.
Table 7: Membership operators
Operator Description
In True if the value is found in the sequence
Not In True if the value is not found in the sequence

Variables and Constants in the Python Programming Language


This is an alphabet or name that holds values or represents a constant or an expression, or another
variable. It is a symbolic memory location whose value can change during program execution.
Therefore, the variable name can change when the program is running. Examples of variables are
Studentname, Amount_paid, Regno, Department, interest_rate, etc.
Rules for naming variables in Python
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• 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)
Attributes of Variables
1. Name: a tag used to identify the variable
2. Address: location in the memory where the variable is stored
3. Type: the type of data the variable may store. The type determines the possible range of
values the variable can store, as well as how much space in memory the variable will occupy.

29 | P a g e
4. Value: the contents of the memory starting at the address and having the size as determined
by the type.
5. Scope: where in a program a variable is visible, i.e. where it can be referenced;
6. Lifetime: when a program a variable value is visible, i.e. when it can be referenced.
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the value stored in the variable.
For example −
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.

30 | P a g e
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after they
have been set.
x = 5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print ("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is"
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome

Constant variable in the Python programming language


A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely
use constants in Python. Constants are usually declared and assigned on a different module/file.
#Declare constants in a separate file called [Link]
PI = 3.14
GAVITY = 9.8
Then, they are imported to the main file
#inside [Link], import the constants

31 | P a g e
Import constant
print([Link])
print([Link])

Expression in Python Programming


An expression is a combination of values, variables, and operators. An expression is evaluated
using the assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y
20
Python also defines expressions that only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable, module, or object is an
identifier.
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are string literals, byte literals, integer literals, floating
point literals, and imaginary literals.
Operators: In Python, you can implement the following operations using the corresponding
tokens.
Python statement

32 | P a g e
A statement is an instruction that the Python interpreter can execute. We normally have two basic
statements: the assignment statement and the print statement. Some other kinds of statements that
are if statements, while statements, and for statements are generally called control flows.
Examples:
An assignment statement creates new variables and gives them values:
>>> x=10
>>> college="mrcet."
A print statement is something that is an input from the user, to be printed/displayed on the screen
or monitor.
>>> print ("mrcet college")
mrcet college

Data Type, Data Type Declaration, and Built-In Functions in Python


Data type is useful to define the type of data the variable can hold, such as integer, float, string,
etc. A data type is a set of values and a set of operations defined on the values. There are twelve
(12) primitive (built-in) data types in Visual Basic. These include int, float, Boolean, string, list,
tuple, set, and dictionary.
Python Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Python Float: A Float, or "floating point number," is a number, positive or negative, containing
one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.
Python Boolean: Objects of the Boolean type may have one of two values, True or False.
Python String: Strings in Python are identified as a contiguous set of characters represented in
quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to the screen using the print function.
For example: print("hello").
Python List: It is a general-purpose data structure most widely used in data structures List is a
collection that is ordered and changeable, and allows duplicate members. (Grow and shrink as
needed, sequence type, sortable). To use a list, you must declare it first. Do this using square
brackets and separate values with commas. A list can be constructed/created in many ways.

33 | P a g e
Example:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1= (1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Python Tuple: is an ordered sequence of items as a list. The only difference is that tuples are
imutable, and once created cannot be modified. Tuples are used to write-protected data and are
usually faster than list as they cannot change dynamically. Tuple is defined within parentheses ()
where items are separated by commas.
Example:
t= (5, “program’, 1+3j).
A Python set is an unordered collection of unique items. Set is defined by values separated by a
comma inside braces {}. Items in a set are not ordered.
Example:
{5, 2, 3, 1, 4}.
Python Dictionary: is an unordered collection of key-value pairs. It is generally used when we
have a huge amount of data. Dictionaries are optimized for data retrieval. The key value to retrieve
the data must be known. In python, dictionary are defined within braces {} with each item being
a pair in the form of key: value. Key and value can be of any type.
Example:
>>>d = {1: ‘value’. ‘key’:2}
>>>type(d)
<class ‘dict’>

34 | P a g e
Built-in Functions in Python Programming
The Python Programming language contains various built-in functions to be used on variables for
performing different functions, such as numeric functions, string functions, and type conversion.
Python functions are shown in Table 8.
Table 8: Built-in functions examples in Python
Built-in function descriptions
abs() Return the absolute value of a number
ascii() Return a readable version of an object. Replaces non-ASCII characters
with the escape character
bin() Return the binary version of a number
bool() Return the Boolean value of the specified object
chr() Return a character from the specified Unicode code
complex() Return a complex number
dict() Return a dictionary array
dir() Return a list of the specified object’s properties and methods
eval() Evaluate and execute an expression
format() Format a specified value
hex() Convert a number into a hexadecimal value
float() Return a floating-point number
input() Allow user input
int() Return an integer number
len() Return the length of an object
max() Return the largest value in a set of values
min() Return the smallest value in a set of values
pow() Return the value of x to the power of y
oct() Convert a number into an octal number
round() Round a number to the nearest value. Round (5.762389, 2) = 5.77
sorted() Return a sorted list
str() Return a string object
sum() Sum the items of an iterator. x = (1, 2, 3, 4, 5, 6, 7, 8) ; sum(x) = 34

35 | P a g e
CHAPTER FOUR
INTRODUCTION TO STRING PROCESSING AND HANDLING IN PYTHON

Strings
A string is one of the most fundamental data types in Python and represents a sequence of
characters. Strings are commonly used to store and manipulate text data such as names,
messages, identifiers, file paths, and even formatted numerical output. In Python, strings are
enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or
"""...""") for multi-line text.
Every string in Python is an immutable sequence, meaning that once created, its characters
cannot be modified directly. Instead, any transformation results in a new string. Understanding
how to work effectively with strings is essential because text processing is a core part of many
programming tasks—from simple data entry to complex natural language processing.

String Indexing and Slicing


Because strings are sequences, Python allows you to access individual characters or extract parts
of the string using indexing and slicing.
2.1 String Indexing
Indexing refers to retrieving a single character from a string using its position. Python uses zero-
based indexing, meaning the first character is at position 0.
Example:
text = "Python"
text[0] # 'P'
text[1] # 'y'
text[5] # 'n'
Indexing is useful when you need to identify or extract specific characters, such as the first letter
of a name or the last character in a word.
String Slicing
Slicing allows you to extract a substring—that is, a portion of the full string. The syntax is:
string[start : stop : step]
• start: index where the slice begins

36 | P a g e
• stop: index where the slice ends (not included)
• step: (optional) indicates spacing between characters
Examples:
text = "Programming"
text[0:7] # 'Program'
text[3:10] # 'grammin'
text[:6] # 'Progra' (from beginning)
text[6:] # 'mming' (to the end)
text[:] # entire string
Using a step value:
text[0:10:2] # 'Pormn' (every second character)
A common slicing task is reversing a string:
text[::-1] # 'gnimmargorP'
Understanding slicing is essential for extracting meaningful information from large text, such as
separating filenames, isolating prefixes, or cleaning data.

Common String Methods


Python provides many built-in string methods for performing transformations, checks, and
formatting. These methods do not modify the original string due to immutability—they return
new strings.
Below are commonly used categories of string methods:

1. Case Conversion Methods


These methods change the case of letters in a string.
• upper(): converts all characters to uppercase
• lower(): converts all characters to lowercase
• title(): capitalizes first letter of each word
• capitalize(): capitalizes the first character only
• swapcase(): switches uppercase to lowercase and vice versa
Example:
"python programming".title() # 'Python Programming'

37 | P a g e
2. Searching and Checking Methods
These helps determine whether a string contains certain characters or patterns.
• find(substring) — returns index of first occurrence or -1
• rfind(substring) — searches from the right
• startswith(text) — checks the beginning of string
• endswith(text) — checks the end of string
• count(substring) — counts occurrences
Example:
"banana".count("a") # 3

3. Validation Methods
These boolean methods answer questions such as “Is this string numeric?” They do not change
the string.
• isalpha() — checks if all characters are letters
• isdigit() — checks if all characters are digits
• isalnum() — letters or digits
• isspace() — contains only whitespace
• islower() — all characters are lowercase
• isupper() — all characters are uppercase

4. Modification and Cleaning Methods


Useful for text processing and cleanup.
• strip() — removes surrounding whitespace
• lstrip() — removes leading spaces
• rstrip() — removes trailing spaces
• replace(old, new) — replaces occurrences
• split(delimiter) — splits a string into a list
• join(list) — joins list items into a string
Example:
“ data science ".strip() # 'data science'

38 | P a g e
"one,two,three".split(",") # ['one', 'two', 'three']
These methods are used heavily in data cleaning, user input validation, and file processing.

Escape Characters and Formatted Output (f-Strings)


1. Escape Characters
An escape character is a special sequence used to represent characters that cannot be typed
directly or would otherwise conflict with syntax.
Common escape characters include:
• \n — newline
• \t — tab
• \\ — backslash
• \' — single quote
• \" — double quote
Example:
print("Hello\nWorld") # prints on two lines
print("Name:\tHenry") # tab space
Escape characters allow you to format text output neatly and include characters that would
normally end a string.

2. Formatted Output with f-Strings


Python's f-strings offer a clear, concise way to embed expressions inside string literals.
Introduced in Python 3.6, f-strings are now the recommended way to format output.
Syntax:
f"some text {expression}"
Example:
name = "Henry"
age = 21
print(f"My name is {name} and I am {age} years old.")
You can embed calculations:
print(f"5 + 10 = {5 + 10}")
You can format numbers:

39 | P a g e
pi = 3.1415926535
print(f"Pi rounded to two decimals: {pi:.2f}")
Advantages of f-strings:
• More readable
• Faster than older methods like format()
• Allow inline expressions

Basic Text Processing Tasks


String manipulation is essential in many real-world tasks. Below are several basic text processing
tasks students commonly encounter.

1. Counting Characters, Words, and Lines


Counting characters:
text = "Hello world"
len(text) # 11
Counting words:
len([Link]()) # 2

2. Converting User Input to a Standard Form


Example: ensuring names always start with an uppercase:
name = input("Enter your name: ").strip().title()
Result:
Entering "henry nweke" becomes "Henry Nweke".

3. Checking for Patterns


Example: verifying if an email contains "@" and ".":
email = "user@[Link]"
if "@" in email and "." in email:
print("Valid email structure")

40 | P a g e
4. Text Cleaning
Useful in data science:
dirty = " Hello,,, world!! "
cleaned = [Link]().replace(",", "").replace("!", "")

5. Reversing and Palindrome Checking


Reversing:
rev = text[::-1]
Palindrome check:
text == text[::-1]
6. Extracting Substrings for Practical Use
Example: extracting year from a date string:
date = "2025-11-27"
year = date[:4] # '2025'

7. Joining and Splitting for Structured Data


Transforming comma-separated values:
csv_text = "john,doe,25"
data = csv_text.split(",") # ['john', 'doe', '25']
Joining words:
" ".join(["Data", "Science", "Course"]) # 'Data Science Course.'

41 | P a g e
CHAPTER FIVE
PYTHON PROGRAM CONTROL STRUCTURE
Control Structures
In programming, control structures determine the flow of execution of statements in a program.
Without control structures, programs would run sequentially from top to bottom without any
ability to make decisions or repeat actions. There are two basic control structures in Python
programming. These include the Conditional Statement and Loop Statement
A. Conditional Statement
The conditional statements allow a program to respond differently depending on certain
conditions.
Conditional (decision-making) structures enable Python to evaluate information and choose
actions, much like humans decide based on circumstances. For example:
• A grading system that assigns a grade depending on a score
• A banking application that checks if a user has enough balance before withdrawing
• A login system that checks whether a password is correct
Understanding conditions is essential for writing logical, interactive, and realistic programs.

Boolean Logic and Truth Values


1. Boolean Data Type
Python uses the Boolean data type (bool) to represent truth values. A Boolean value can be either:
• True
• False
These values are the result of comparisons or logical operations.
2. Comparison Operators
Comparison operators evaluate expressions and return Boolean values.
Operator Meaning Example Result

== equals 5 == 5 True

!= not equal 5 != 3 True

> greater than 10 > 2 True

< less than 3<1 False

42 | P a g e
Operator Meaning Example Result

>= greater than or equal 7 >= 7 True

<= less than or equal to 2 <= 2 True


These operators form the basis for writing conditions.
3. Logical Operators
Logical operators combine multiple conditions.

Operator Meaning Example Result

and True only if both conditions are True (5 > 3) and (2 < 4) True

or True if at least one condition is True (5 > 3) or (2 > 4) True

not Reverses truth value not(True) False

These helps build complex decision-making logic.

4. Truthiness and Falseness


Python considers some values as True or False in a Boolean context:
Falsey values include:
• 0
• 0.0
• "" (empty string)
• [] (empty list)
• {} (empty dictionary)
• None
• False
Anything else is truthy.
Example:
if "Hello":
print("This is truthy!") # will run

43 | P a g e
if, elif, else Statements
Conditional statements allow Python to execute code only when certain conditions are met.
1. The if Statement
The simplest form:
if condition:
statement(s)
Python evaluates the condition; if it's True, the indented block runs. If not, Python skips it.
Example:
age = 20
if age >= 18:
print("You are an adult.")

2. The if–else Statement


Adds an alternative block when the condition is False.
if condition:
statements_if_true
else:
statements_if_false
Example:
num = -3
if num > 0:
print("Positive number")
else:
print("Not positive")

3. The if–elif–else Chain


Used when checking multiple conditions.
if condition1:
block1
elif condition2:

44 | P a g e
block2
elif condition3:
block3
else:
final_block
Example:
score = 75

if score >= 70:


print("Excellent")
elif score >= 50:
print("Good")
elif score >= 40:
print("Pass")
else:
print("Fail")
Python checks conditions in order and executes the first True block.

Nested Conditionals
A nested conditional is an if statement inside another if. It is useful when decisions depend on
multiple layers of checking.
Example:
age = 18
has_id = True

if age >= 18:


if has_id:
print("Access granted.")
else:
print("ID required.")
else:

45 | P a g e
print("You must be 18 or older.")
Nesting should be used carefully to maintain readability.

Common Decision-Making Patterns


1. Range Checking
Frequently used to test if a value falls within a range.
Example:
temp = 30
if 20 <= temp <= 35:
print("Comfortable temperature")

2. Multiple Conditions with and/or


Example:
if age >= 18 and nationality == "Nigerian":
print("Eligible voter")
Example using or:
if day == "Saturday" or day == "Sunday":
print("Weekend!")

3. Flag Variables
Flags track a condition using Boolean values.
is_logged_in = False
if password == "admin123":
is_logged_in = True

if is_logged_in:
print("Welcome!")

4. Sentinel Decisions
Used to stop a loop or process when a special value is encountered.
Example:

46 | P a g e
num = input("Enter a number (or 'quit'): ")
if num == "quit":
print("Exiting program...")

5. Multiple Independent Conditions


Sometimes you test many separate conditions rather than a chain.
if x == 0:
print("Zero")
if x % 2 == 0:
print("Even")

Practical Examples of Conditional Statements


1. Grading System (if–elif–else)
A common classroom task is assigning grades based on score ranges.
Program Description
• Input: Student score
• Output: Letter grade (A, B, C, D, F)
• Uses chained conditions
Example Code
score = int(input("Enter your score: "))
if score >= 70:
print("Grade: A")
elif score >= 60:
print("Grade: B")
elif score >= 50:
print("Grade: C")
elif score >= 45:
print("Grade: D")
else:
print("Grade: F")
Logic Explanation

47 | P a g e
Python checks top to bottom until one condition is True. If no condition matches, the else executes.

2. Even or Odd Number Checker


num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Shows the simplest use of conditions.

3. Simple Login System (Nested Conditionals)


username = input("Username: ")
password = input("Password: ")

if username == "admin":
if password == "12345":
print("Login successful")
else:
print("Incorrect password")
else:
print("User not found")

4. Basic Eligibility Checker


Example: voting eligibility in Nigeria.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

48 | P a g e
5. Transportation Decision Program
distance = 10
if distance < 3:
print("Walk")
elif distance <= 10:
print("Take a motorcycle")
else:
print("Use public transport")

6. Student Admission Decision (Multiple Conditions)


score = int(input("UTME score: "))
state = input("State of origin: ")
if score >= 200 and [Link]() == "abuja":
print("Congratulations! You meet the requirements.")
else:
print("Admission not granted.")

B. Loop Structure
Control structures allow a program to make decisions and repeat certain actions. In the previous
lesson, you studied conditional statements such as if, elif, and else, which help a program choose
between alternatives.
In this lecture, we explore a different category of control structures: loops.
Loops allow us to execute a block of code repeatedly, either a specific number of times or until a
particular condition is met. Many real-world problems, such as processing items in a list,
generating repeated output, or performing calculations, require repeating actions, making loops a
fundamental part of programming. A loop is a control structure used to perform repeated tasks.
Python provides two primary looping constructs:
1. While loop: repeats a block of code as long as a condition remains true.
2. for loop: iterates over a sequence (such as a list, string, or range of numbers).
Loops help automate repetitive tasks and simplify complex operations.
while Loop

49 | P a g e
A while loop executes as long as its Boolean condition is true. It checks the condition before
running the loop body, making it a pre-test loop.
Syntax
while condition:
# code to repeat
The loop continues until the condition becomes false.
Example 1: Counting from 1 to 5
count = 1
while count <= 5:
print(count)
count = count + 1
Explanation
• The loop begins with count = 1.
• It continues printing numbers as long as count <= 5.
• Each iteration increases the counter by 1.
• When the count becomes 6, the condition is false, and the loop stops.
Example 2: Simple Input Validation
password = ""
while password != "admin123":
password = input("Enter password: ")
print("Access granted.")

Here, the loop keeps asking for a password until the user enters the correct one.
The for Loop
A for loop is used when you want to iterate over items in a sequence, such as:
• lists
• strings
• ranges
• tuples
• dictionaries (keys/values)
Syntax

50 | P a g e
for item in sequence:
# code to repeat

Example 1: Looping Through a List


fruits = ["apple", "banana", "orange"]
for f in fruits:
print(f)

Example 2: Looping Through a Range of Numbers


for num in range(1, 6):
print(num)
This prints the numbers 1 to 5 (range end is exclusive).
Example 3: Looping Through a String
for letter in "Python":
print(letter)

Loop Control Statements


Sometimes we need to change how a loop behaves—skip certain steps, stop early, or do nothing
temporarily. Python provides three control statements:
a. break – Exit the loop immediately
Used when you want to stop looping even if the loop condition or sequence has not finished.
Example: Searching for a Number
for num in range(1, 10):
if num == 5:
break
print(num)
Stops printing once it reaches 5.

b. continues: Skip the current iteration and move to the next


Example: Printing Only Odd Numbers
for num in range(1, 10):

51 | P a g e
if num % 2 == 0:
continue
print(num)
When the number is even, the loop skips printing.
c. pass – Placeholder; does nothing
Used when the programmer wants to write code later.
for num in range(5):
pass # to be implemented later

Iterating Over Sequences


Python loops work especially well with sequences.
Iterating Over Lists
names = ["Ada", "Chidi", "Bola"]
for name in names:
print("Hello,", name)
Iterating Over Strings
for char in "Hello":
print(char)
Iterating with Index Using range()
items = ["rice", "beans", "yam"]
for i in range(len(items)):
print(i, items[i])

Practical Applications of Loops


Some examples of applications of Loop.
Practical Example 1: Multiplication Tables
Loops make it easy to display multiplication tables.
Example: Multiplication Table for 5
for i in range(1, 13):
print(f"5 x {i} = {5 * i}")
Example: Full 1–12 Multiplication Table

52 | P a g e
for num in range(1, 13):
print(f"\nMultiplication Table for {num}")
for i in range(1, 13):
print(f"{num} x {i} = {num * i}")
This uses nested loops, where one loop is inside another.

Practical Example 2: Simple Number Guessing Game


secret = 7
guess = 0

while guess != secret:


guess = int(input("Guess a number (1-10): "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")

print("Correct! Well done.")


This program continues until the user guesses the correct number.

Practical Example 3: Sum of First N Numbers


n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"The sum of numbers from 1 to {n} is {total}.")

Practical Example 4: Countdown Timer


count = 10
while count > 0:
print(count)

53 | P a g e
count -= 1
print("Blast off!")

Common Looping Patterns


Counting Upwards
for i in range(10):
print(i)
Counting Downwards
for i in range(10, 0, -1):
print(i)
Accumulation Pattern (Summing values)
total = 0
for num in [3, 5, 7]:
total += num
print(total)
Searching Pattern
found = False
for item in ["apple", "banana", "orange"]:
if item == "banana":
found = True
break

54 | P a g e

Common questions

Powered by AI

Python implements polymorphism primarily through inheritance and dynamic typing, allowing different classes to define methods with the same name or interface. This enables objects from different classes to be treated uniformly. An example is having a base class 'Shape' with a method 'draw' and derived classes like 'Circle' and 'Square' that implement 'draw' in their own way. A function that calls 'draw' on a 'Shape' can accept any derived class object, making operations versatile and extensible.

Using nested conditionals sparingly in Python is important for maintaining code readability and reducing complexity. Deeply nested structures can become difficult to follow and increase the likelihood of errors. An example of their application is a login system where access depends on both user credentials being valid—nesting checks for username and password within conditional blocks can clarify dependencies but should be kept shallow to aid understanding and simplify debugging.

Polymorphism and inheritance enhance code reusability by allowing new classes to inherit properties and behaviors from existing classes. Polymorphism enables objects to be treated as instances of their parent class, allowing for generic programming. Subtype polymorphism allows derived class objects to substitute for base class objects. This mechanism reduces redundancy as common code needs to be written only once in the base class, and new or extended functionality can be added in derived classes without altering existing code.

Control structures in Python determine the flow of execution within a program, allowing for decision-making and repetitive tasks. The two primary types of control structures are conditional statements and loops. Conditional statements enable alternate paths of execution (e.g., if, elif, else) based on Boolean conditions, while loops (e.g., for and while) execute blocks of code repeatedly until a specified condition is no longer satisfied. These structures allow a program to perform complex operations and respond dynamically to different inputs.

In Python's object-oriented paradigm, a class serves as a blueprint for creating objects. It defines the structure and behaviors that its instances (objects) will have, specifying attributes and methods common to all objects of a type. An object is an instance of a class, holding unique data defined according to the class blueprint. While a class is abstract, defining the potential properties and behaviors, an object is concrete, embodying these traits with actual values and executable methods.

Message passing in Object-Oriented Programming is a form of communication where objects send and receive messages to invoke behavior. It involves specifying the receiving object, the function to execute, and any input data. This mechanism is significant because it encapsulates interactions, enabling objects to interact without having detailed knowledge of each other's data or methods—enhancing modularity and flexibility in code design.

In Python, the for loop is used to iterate over elements in data structures like lists, tuples, strings, or ranges. It allows accessing each element directly, making operations on collections efficient and concise. The for loop simplifies looping through sequences by abstracting loop control mechanisms, reducing errors, and improving code readability. It is especially advantageous for tasks that involve uniform operations on elements, such as summing numbers, modifying lists, or constructing new sequences.

In a Python class, there are two main types of attributes: instance attributes and class attributes. Instance attributes are unique to each object, defined in the __init__ method, and represent data specific to that instance (e.g., a student's name or age). Class attributes are shared across all objects of the class, defined within the class body, and represent common data applicable to all instances (e.g., a school's name)

Encapsulation contributes to software security by restricting direct access to an object's internal state and protecting data integrity. This is achieved by wrapping data and the methods operating on that data within a single unit, thereby enforcing controlled access. By limiting exposure of internal implementations, encapsulation reduces the risk of unintentional or malicious interference.

The core objectives of Object-Oriented Programming (OOP) are to make programs more modular, reusable, organized, and easier to maintain. These objectives are achieved through several key features: robustness to handle unexpected inputs and errors; adaptability to evolve with changing technological conditions; reusability to accelerate development and reduce redundancy through inheritance; maintainability by organizing code into independent objects; abstraction to hide complex details from users; security through encapsulation and data hiding; and modularity by breaking systems into smaller, manageable units.

You might also like