0% found this document useful (0 votes)
11 views49 pages

Module 1 - Algorithmic Thinking With Python

Module 1 focuses on algorithmic thinking with Python, emphasizing problem-solving strategies such as trial and error, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including understanding the problem, formulating a model, developing algorithms, and evaluating solutions. The module also distinguishes between well-defined and ill-defined problems, highlighting the importance of selecting appropriate strategies based on the nature of the problem.

Uploaded by

andrewgeo2006
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)
11 views49 pages

Module 1 - Algorithmic Thinking With Python

Module 1 focuses on algorithmic thinking with Python, emphasizing problem-solving strategies such as trial and error, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including understanding the problem, formulating a model, developing algorithms, and evaluating solutions. The module also distinguishes between well-defined and ill-defined problems, highlighting the importance of selecting appropriate strategies based on the nature of the problem.

Uploaded by

andrewgeo2006
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
You are on page 1/ 49

Tab 1

MODULE 1- ALGORITHMIC THINKING WITH PYTHON

Module 1- Syllabus

PROBLEM-SOLVING STRATEGIES:- Problem-solving strategies defined, Importance of


understanding multiple problem-solving strategies, Trial and Error, Heuristics, Means-Ends
Analysis, and Backtracking (Working backward).
THE PROBLEM-SOLVING PROCESS:- Computer as a model of computation, Understanding
the problem, Formulating a model, Developing an algorithm, Writing the program, Testing the
program, and Evaluating the solution.
ESSENTIALS OF PYTHON PROGRAMMING:- Creating and using variables in Python,
Numeric and String data types in Python, Using the math module, Using the Python Standard
Library for handling basic I/O - print, input, Python operators and their precedence.

1.1 PROBLEM-SOLVING STRATEGIES

1.1.1 Problem-solving strategies defined

Problem solving is the process of identifying an existing problem, determining the root
cause or causes of the problem, deciding the best course of action in order to solve the
problem, and then finally implementing it to solve the problem.

Problem-solving is used to solve our everyday basic needs; and there are many ways to
solve problems. The countless number of everyday solutions are as diverse and
specialized as the problems themselves.

Effective problem-solving requires you to identify the problem, select the right
process to approach it and follow a plan tailored to the specific issue you are trying
to solve.

Problem-solving is a key skill in programming that goes beyond just writing code – it's
about systematically tackling complex challenges to find effective solutions. The process
begins by understanding the problem thoroughly, which involves identifying its scope.
constraints, and requirements. This understanding lays the groundwork for creating a
solution. Next, you plan how to solve the problem by choosing the right approach,
algorithms, and data structures. Breaking the problem into smaller parts makes it easier to
manage Critical thinking helps in evaluating different solutions, while creativity is
important when standard methods don't work.

1
Finding the best solution within gıven constraints, like time and resources, is crucial. An
optimal solution is not only correct but also efficient and easy to maintain. Anticipating
potential issues and planning for them ensures the solution is reliable. Understanding
algorithms and data structures is essential because they guide how problems are solved
and how data is handled. Finally, good software design principles ensure that the solution
is well-structured, easy to maintain and adaptable to future changes.

1.1.2 Importance of understanding multiple problem-solving strategies

Problem solving techniques are great in variation and are nearly as important as the
problem solving itself. Without having proper techniques to begin the problem solving
process, individuals would find it much more difficult to do effectively. It Includes: trial
and error, algorithms and heuristics, means-ends-analysis, etc. Choosing the correct
technique for the given situation is dependent on the individual, their experience and their
resourcefulness.

Given a problem—be it a complex mathematical problem or a broken printer, the main


concern is mapping out a strategy to solve or fix it. Finding a solution implies that the
problem must first be clearly identified. After that, one of the many problem solving
strategies can be applied, hopefully resulting in a solution.

Problems themselves can be classified into two different categories known as ill-defined
and well-defined problems.

Ill-Defined Problems
These problems lack a clear goal or defined constraints, and the path to a solution is not
immediately apparent.
An ill-defined problem is a problem that has:
1.​ Unclear goals: The objective of the problem may be vague or open to
interpretation.
2.​ Ambiguous constraints: The rules and conditions for solving the problem are not
well-specified, and there may be multiple ways to approach it.
3.​ Multiple or unclear solutions: The problem may have several possible solutions,
or it may be difficult to determine the best or correct solution.

Examples
1.​ Designing a marketing campaign to improve a company’s brand image. The goal
(improve brand image) is broad, the constraints (budget, target audience, etc.)
may be flexible or not fully defined, and there are many potential strategies and
outcomes.

2
2.​ Where should I go on my next vacation? The problem lacks specific criteria for
what makes a destination "best. Factors like budget, activities, climate. and
personal preferences not clearly outlined, and the decision is highly subjective.
3.​ Design A new product that people will love. The problem is broad and lacks
specific guidelines or constraints. There is no clear definition of what the product
should do, who the target audience is or what “people will love" means, leading to
many possible solutions.
4.​ How can we improve workplace morale? The problem is vague with no clear
metrics for what constitutes "improved morale”. Various factors like company
culture, communication, and employee satisfaction are involved, and there is no
single correct solution.
5.​ Deciding on the best way to improve company work culture Or solving complex
societal issues are ill-defined problems. They often require a more exploratory
approach, with multiple possible solutions and ongoing adjustments based on new
insights or feedback.

Well-Defined Problem
These are the problems where the goal is clear, constraints are known and there is a
Specific path to the solution
A well-defined problem is a problem that has:
1.​ Clear goals: The objective of the problem is explicitly stated.
2.​ Defined constraints: The rules and conditions under which the problem must be
solved are clear and specific.
3.​ Definite solutions: There is a clear, correct answer or set of answers to the
problem.

Examples
1.​ Solving a math problem, like x+2=5. The goal (find x), the constraints (use basic
arithmetic), and the solution (x=3) are all clear and unambiguous.
2.​ Assemble a bookshelf using the provided parts and instructions. The problem has
a clear goal (assemble the bookshelf), specific steps to follow (instructions), and a
clear end result (a fully assembled bookshelf).
3.​ Sort the list of numbers [5, 3, 8, 1, 21 in ascending order. Why Well-Defined: The
problem has a clear objective (sort the numbers), specific constraints(use the
given list),
And a single correct outcome ([1,2,3,5,8])

3
Understanding these types of problems helps you select the appropriate problem-solving
strategy and effectively address challenges you face.

Understanding a variety of problem-solving strategies is crucial because different types of


problems require different approaches. It is important to have a clear understanding of
how a variety of problem-solving strategies work because different problems are typically
required to be approached in different ways to find the best solution.Mastering various
problem-solving strategies allows for the selection of the right plan of action when faced
with challenges in the future. This helps to solve problems faster and develop stronger
critical thinking skills.

Problem-Solving Strategies:-
Effective problem solving involves selecting and applying appropriate strategies to
identify, analyse and resolve issues. The different problem solving strategies are trial and
error, heuristic, means-end analysis and backtracking.

1.1.3 Trial and Error

A trial-and-error approach to problem-solving involves trying a number of different


solutions and ruling out those that do not work. This approach can be a good option if
there are a limited number of possibilities to consider. For example, in the case of a
broken printer, one could check the ink levels, and if that doesn’t work, check to ensure
the paper tray isn’t jammed, or verify that the printer is properly connected to a laptop.
Using trial and error, different solutions are attempted sequentially until the problem is
solved. Although trial and error is not typically the most time-efficient strategy, it is a
commonly used one.

This approach can be effective if

●​ The problem does not have a clear idea to solve the problem
●​ The Problem isn't too complex or costly if you make a mistake
●​ There are a limited number of possibilities to consider

Limitation

●​ Trial and error can be slow and waste time, especially if there are many potential
solutions or if the problem is complicated.
●​ It doesn't offer a structured method for solving the problem; it's more about
persistence and experimentation. For complex problems, it's often better to use a
more systematic approach to avoid wasting time and resources

4
Example

●​ Broken printer, Restarting phone, turning off WiFi, turning off bluetooth in order
to determine why your phone is malfunctioning
●​ Learning a new skill: When learning to ride a bike, you keep trying different
balance methods until you succeed.
●​ Solving a puzzle without prior knowledge: You try different moves in a jigsaw
puzzle until the pieces fit.
●​ Testing software: Developers use trial and error to fix bugs, trying different code
adjustments until the issue is resolved.
●​ Machine learning - When training a computer to recognize patterns or make
predictions, different models or settings are tested to find the one that gives the
best results.
●​ Finding the correct route: If you're lost in a maze, you try different paths until you
find the exit.
●​ Cooking experiments: Trying different ingredient combinations in a recipe until
the desired taste is achieved.

1.1.4 Heuristic

Heuristics are ways of solving problems using simple rules based on experience. Think of
them as mental shortcuts that help solve problems efficiently. A “rule of thumb” is an
example of a heuristic. Think of heuristics as helpful hints or rules of thumb that guide
you toward a solution faster than starting from scratch. Such a rule saves the person time
and energy when making a decision, but despite its time-saving characteristics, it is not
always the best method for making a rational decision.

Heuristics are used everyday in many areas, like making quick decisions, solving
everyday problems, or even in artificial intelligence. They help by speeding up the
process and making it easier to handle complex problems without getting stuck on every
detail.

The Limitations:

●​ While heuristics can be very useful, they aren't always perfect. Sometimes they
lead you in the right direction but might not find the absolute best solution.
●​ The effectiveness of a heuristic depends on how accurate your rules are. If the
heuristic is based on wrong or incomplete information, it might lead you down the
wrong path.

5
Example

●​ When trying to find the quickest route to a friend's house without a map,
knowledge of the area can be used to estimate the fastest path instead of checking
every possible road. A main road might be chosen over a small street based on the
experience that main roads typically offer faster travel.
●​ In Search Algorithms: In computer science, heuristics help in finding solutions
quickly without having to check every option. For example, in navigation
systems, heuristics help by suggesting the most promising routes to take, so you
don't waste time exploring every possible path. Navigation systems, heuristics
help by suggesting the most promising routes to take, so you don't waste time
exploring every possible path.
●​ Problem solving in math.
●​ Searching online: Using a shortcut like typing keywords instead of writing full
sentences.
●​ Decision making: Buying a product by relying on brand reputation as a shortcut to
judge quality.
●​ Route planning: Taking the "most familiar route" to avoid getting lost even if it's
not the fastest.
●​ Medical diagnosis: Doctors use rules of thumb based on symptoms to diagnose
common diseases.
●​ Game playing: Using game strategies that are known to usually work rather than
calculating every possible move.

1.1.5 Means-Ends Analysis

Means-ends analysis is a problem-solving technique that involves identifying the current


state and the desired goal state, then finding a way to reduce the difference between the
two. This usually involves breaking down the problem into smaller, manageable
sub-goals (or sub-problems) and solving these incrementally.
This strategy involves choosing and analyzing an action at a series of smaller steps to
move closer to the goal. One example of means-end analysis can be found by using the
Tower of Hanoi paradigm. The Tower of Hanoi problem consists of three rods sitting
vertically on a base with a number of disks of different sizes that can slide onto any rod.
The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the
smallest at the top making a conical shape.

The objective of the puzzle is to move the entire stack to another rod obeying the
following rules:
1. Only one disk can be moved at a time.

6
2. Each move consists of taking the upper disk from one of the stacks and placing
it on top of another stack or on an empty rod.
3. No larger disc may be placed on top of a smaller disk.

Applying Tower of Hanoi to solve a strategy which involves choosing and analyzing an
action at a series of smaller steps to move closer to the goal.
The process begıns by establishing the end goal and then determining the current state.
The problem solver then identifies the means or actions necessary to bridge the gap
between the current state and the goal. This often involves setting sub-goals that are
closer to the end goal and tackling these sub-goals one at a time. By systematically
addressing each sub-problem, the problem solver can progressively move toward the
overall solution.
Means-end analysis is a method for solving problems by figuring out the steps needed to
move from where you are now to where you want to be. Here's a simple way to
understand how it works:

1. Setting the Goal: First, decide what is the end goal.For example, consider the Tower of
Hanoi puzzle with 3 disks and 3 pegs. The goal is to move all three disks from the first
peg to the third peg, following the rules of the puzzle.

2. Understanding the Current State: Next, look at the current situation. The current state
involves all three disks stacked on the first peg in order of size, with the largest disk at
the bottom and the smallest at the top.

3. Identifying the Steps: Figure out what actions or steps need to be taken to bridge the
gap between the starting point and your goal. The necessary actions to achieve the goal
include moving disks between pegs while adhering to the rules that only one disk can be
moved at a time and a larger disk cannot be placed on a smaller disk.
4. Breaking Down the Problem: The problem is broken down into smaller tasks and each
of these smaller tasks brings closer towards the final goal. Such as
●​ Moving the smallest disk to the third peg.
●​ Shifting the second disk to another peg.
●​ Continuing to move disks in a sequence that allows for the movement of larger
disks as needed.

5. Step-by-Step Progress: By tackling each of these smaller tasks one at a time,we


steadily move closer towards the final goal.
Here are the steps for Means-End Analysis for the Tower of Hanoi with 3 disks:
●​ Goal: Move all 3 disks from Peg A to Peg C.
○​ Sub-goal 1: Move the top 2 disks from Peg A to Peg B.

7
○​ Sub-goal 2: Move the largest disk (Disk 3) from Peg A to Peg C.
○​ Sub-goal 3: Move the 2 disks from Peg B to Peg C.

This breakdown in Means-End Analysis ensures that each move is purposeful and based
on sub-goals, leading to an efficient solution.
The minimal moves required to solve a Tower of Hanoi puzzle is 2n – 1, where n is the
number of disks. For example, if there were 14 disks in the tower, the minimum amount
of moves that could be made to solve the puzzle would be 214 – 1 = 16,383 moves.

This approach can be effective if


Goals are clear: This strategy works best when you know exactly what you want to
achieve, but the exact steps to achieve it aren't obvious. It provides a clear plan breaking
down the journey into manageable steps.

Limitation
Complex Problem lt can be tricky when the problem is very complex or when it's hard to
break down into smaller parts.

Examples
●​ In AI and Technology: means-end analysis is used to model human
problem-solving behavior, especially when the end goal is clear but the steps to
reach it are not. This approach is effective in automated planning and
decision-making systems, where a sequence of actions is needed to achieve

8
specific objectives. For instance, a robot can use this method to determine the
steps required to pick up an item and place it in a designated location.
●​ Planning a trip: Breaking down a trip into smaller steps like booking a flight,
reserving a hotel, etc., to reach the ultimate goal.
●​ Goal setting: Breaking down career goals into smaller steps like gaining specific
qualifications.
●​ Writing an essay: You focus on creating an outline, then write the introduction,
followed by paragraphs, to complete the final essay.
●​ Project management: Breaking down a project into smaller tasks, and solving
them one by one until the entire project is completed.
●​ Software development: Breaking down a large programming task into subtasks
and addressing each sub-task to complete the final application.

1.1.6 Backtracking Algorithms

Backtracking algorithms are like problem-solving strategies that help explore different
options to find the best solution. They work by trying out different paths and if one
doesn’t work, they backtrack and try another until they find the right one. It’s like solving
a puzzle by testing different pieces until they fit together perfectly.
It is commonly used in situations where you need to explore multiple possibilities to
solve a problem, like searching for a path in a maze or solving puzzles like Sudoku.
When a dead end is reached, the algorithm backtracks to the previous decision point and
explores a different path until a solution is found or all possibilities have been exhausted.

How Does a Backtracking Algorithm Work?


A backtracking algorithm works by recursively
exploring all possible solutions to a problem. It starts by
choosing an initial solution, and then it explores all
possible extensions of that solution. If an extension
leads to a solution, the algorithm returns that solution.
If an extension does not lead to a solution, the
algorithm backtracks to the previous solution and tries a
different extension.

The following is a general outline of how a backtracking algorithm works:


1.​ Choose an initial solution.
2.​ Explore all possible extensions of the current solution.
3.​ If an extension leads to a solution, return that solution.

9
4.​ If an extension does not lead to a solution, backtrack to the previous solution and
try a different extension.
5.​ Repeat steps 2-4 until all possible solutions have been explored.

Example of Backtracking Algorithm

Example: Finding the shortest path through a maze

Input: A maze represented as a 2D array, where 0 represents an open space and 1


represents a wall.

Algorithm:

1.​ Start at the starting point.


2.​ For each of the four possible directions (up, down, left, right), try moving in that
direction.
3.​ If moving in that direction leads to the ending point, return the path taken.
4.​ If moving in that direction does not lead to the ending point, backtrack to the
previous position and try a different direction.
5.​ Repeat steps 2-4 until the ending point is reached or all possible paths have been
explored.

This approach can be effective if

●​ There are multiple possible solutions to the problem.


●​ The problem can be broken down into smaller subproblems.
●​ The subproblems can be solved independently.
●​ Backtracking is very thorough because it ensures all possible options are
explored. This means you won't miss the right solution.

Limitation

Time-Consuming: This method can be slow, especially if there are many possible options
to check. It might take a lot of time to find the right solution.

Example

●​ Solving a Sudoku puzzle: If you place a number incorrectly, you backtrack and try
a different number.

10
●​ Solving mazes: If you hit a dead end in a maze, you backtrack to a previous
choice point and choose a different path.
●​ Crossword puzzles: When a word doesn’t fit, you backtrack and choose different
letters.
●​ Finding a file in a directory: If searching in one folder doesn't work, you
backtrack and explore other directories.
●​ Chess problem solving: If a move leads to a losing position, you backtrack and
choose a different move.
●​ Finding the shortest path through a maze
●​ Scheduling problems
●​ Resource allocation problems
●​ Network optimization problems

11
1.2 THE PROBLEM-SOLVING PROCESS

Regardless of the field of study, computer science focuses on solving problems using
computers. Therefore, it is crucial to first understand the computer’s information
processing model. The problems to be solved can come from real-world scenarios or
abstract concepts. A standard, systematic approach to problem-solving is essential. The
model shown in Fig. 1-2-1 assumes a single CPU (Central Processing Unit). However, as
many modern computers have multiple CPUs, the model can be imagined as being
duplicated multiple times within the computer.

A typical single CPU processes information as depicted in the diagram. Problems are
solved on a computer by receiving user input (such as keyboard or mouse data, or game
control movements), processing that input, and then producing output (such as images,
text, or sound). In some cases, the input and output data may involve hard drives or
network devices.

12
1.2.1 Computer as a model of computation

In the context of problem-solving, the model in Fig.1- 2-1 can be applied by assuming
that some form of input information is provided, which is then processed to produce the
desired output as a solution. However, this model is quite simplified. For larger, more
complex problems, the input, process, and output stages may need to be repeated multiple
times in sequence, generating intermediate results that solve parts of the problem but not
necessarily the entire problem. For simple computations, the basic model is sufficient

Problem Solving is the sequential process of analysing information related to a given


situation and generating appropriate response options.

In solving a problem, there are some well-defined steps to be followed. For example,
consider how the input/process/output works on a simple problem:
Example: Calculate the average grade for all students in a class.
1.​ Input: get all the grades ... possibly by typing them in via the keyboard or by
reading them from a USB flash drive or hard disk.
2.​ Process: add them all up and compute the average grade.
3.​ Output: output the answer to either the monitor, to the printer, to the USB flash
drive or hard disk or a combination of any of these devices.

It is noted that the problem is easily solved by simply getting the input, computing
something and producing the output. The steps to the problem solving is mentioned
below

1.​ Understanding the Problem


2.​ Formulating a Model,
3.​ Developing an Algorithm
4.​ Writing the Program,
5.​ Testing the Program
6.​ Evaluating the Solution

13
1.2.2 Understand the Problem

The first step in solving any problem is to ensure that the problem is clearly understood.
It is important to consider the following:

1.​ What input data or information is available?


2.​ What does the data represent?
3.​ In what format is the data provided?
4.​ What is missing from the available data?
5.​ Is all the necessary information available to solve the problem?
6.​ What output information needs to be produced?
7.​ In what format should the result be presented: text, image, or graph?
8.​ What additional requirements are necessary for computation?

In the example above, the input is understood to be a collection of grades. However, it is


important to determine the format of the grades. Each grade could be a number between 0
and 100 or a letter grade ranging from A to F. If it is a number, it could be a whole integer
like 73 or a real number like 73.42. Understanding the format of the grades is essential
for solving the problem.

Consideration must also be given to missing grades. For instance, if some students were
absent during the test, should their grades be included in the average (as if they received a
0) or should they be excluded when calculating the average? Additionally, it is necessary
to determine the desired format for the output. Should the result be a whole number, a
real number, or a letter grade? Is there a need to display the average grade in a pie chart?
These decisions depend on the requirements of the task.

Finally, it is important to understand the type of processing that needs to be performed on


the data, which leads to the next step in problem-solving.

14
1.2.3 Formulating a Model

The next step involves formulating a model for the problem. A model (or formula) is
necessary to compute the average of a set of numbers. If no such formula exists, one must
be developed. To create a model, it is crucial to fully understand the available
information. Assuming the input data consists of integers or real numbers x1, x2, ⋯ , xn
representing grade percentages, the following computational model may be applied:

Average1 = (x1 + x2 + x3 + ⋯ + xn)/n

where the result will range from 0 to 100.

This is very straightforward, assuming that the formula for computing the average of a set
of numbers is known. However, this approach will not work if the input data is a set of
letter grades like B-, C, A+, F, D-, etc., because addition and division cannot be
performed on the letters. This problem solving step must figure out a way to produce an
average from such letters.

After consideration, one possible solution is to assign numerical values to the letter
grades as follows:

A+ = 12, A = 11, A− = 10, B+ = 9, B = 8, B− = 7, C+ = 6, C = 5, C− = 4, D+ = 3, D = 2, D− =


1, F = 0

Assuming these assigned grade numbers are y1, y2, ⋯ , yn the following computational
model may be used:

Average2 = (y1 + y2 + y3 + ⋯ + yn)/n

where the result will range from 0 to 12.

For the output, if it is to be expressed as a percentage, either Average1 can be used


directly, or ([Average2/12]*100) may be applied, depending on the original input format.
If a letter grade is preferred as the output, it may be necessary to use a formula such as
(Average1/100 ∗ 12) or (Average1 ∗ 0.12) or Average2, or directly use Average2 and map
it to a lookup table that corresponds to a grade letter based on a number from 0 to 12.

The key point in this step is determining how to effectively use the available data to
compute a solution.

15
1.2.4 Develop an Algorithm

Once the problem is understood and a model has been formulated, the next step is to
develop a precise plan of what the computer is expected to do.

Definition: Algorithm is a precise sequence of instructions for solving a problem.

To develop an algorithm, the instructions must be represented in a way that is


understandable to a person who is trying to figure out the steps involved. Two commonly
used representations for an algorithm are:

1.​ Pseudocode: pseudocode is a simple and concise sequence of English-like


instructions to solve a problem.
2.​ Flowcharts: A visual representation of the problem-solving process.

Consider the following example for solving the problem of Simple Interest. A flowchart
and pseudocode are given below

Pseudocode is often used as a way of describing a computer program to someone who


doesn’t understand how to program a computer.

Although flowcharts can be visually appealing, pseudocode is often the preferred choice
for algorithm development because:

16
●​ Flowcharts can be difficult to draw neatly, especially when errors occur.
●​ Pseudocode is easier to fit on a single page.
●​ It can closely resemble real programming code, making it easier to later translate
into a program.
●​ Writing pseudocode is faster than drawing flowcharts.

Pseudocode can vary based on the individual who writes it, meaning that one person's
pseudocode is often quite different from another's. The key point is that there are various
ways to write pseudocode, but it is essential for the algorithm to be clearly articulated
without ambiguity regarding the order of the steps. Whether using a flowchart or
pseudocode, an algorithm should be tested by manually going through the steps in mind
to make sure a step or a special situation is not missed out. Often, flaws in an algorithm
can arise from missing special cases.Only after ensuring the algorithm will effectively
solve the problem should the next step be pursued.

1.2.5 Writing the Program

Writing a program is often referred to as "coding" or "implementing an algorithm." The


code (or source code) represents the actual program. Below is an example of a program
that implements an algorithm to calculate the Simple Interest. While the structure of the
code mirrors the algorithm, it may appear less readable and more mathematical.

The source code may differ based on the programming language being used.

Definition 1-2-3: Interpreting converts the high-level language program into machine
code. An interpreter reads the source code line-by-line, converts it into
machine-understandable form, executes the line, and then proceeds to the next line.

The interpreter first reads a Python expression or a statement and verifies that it is valid
with regard to the rules, or syntax, of the language. Any invalid statement is called a
syntax error. When the interpreter encounters such an error, it halts with an error
message.

17
Example incorrect indentation or syntax mistakes, missing colons (:) after control
statements (like if, for, while) will cause the program to fail.

1.2.6 Test the Program

Next step is to inspect the code to verify its correctness. This is called testing.

During testing, the program is evaluated as to whether it produces the desired output. Any
unexpected output is an error. The program should be executed with different sets of
inputs to detect errors. It is impossible to test the program with all possible inputs.

Instead, a smaller set of representative inputs called test suite is identified and if the
program runs correctly on the test suite, then it is concluded that the program will
probably be correct for all inputs.

Running a program is the process of telling the computer to evaluate the instructions.
When a program is run and all is well, you should see the correct output. It is possible
however, that a program works correctly for some set of input data but not for all. If the
output of a program is incorrect, it is possible that the algorithm was not properly
converted into a proper program. It is also possible that the programmer did not produce a
proper algorithm back in step 3 that handles all situations that could arise. Perhaps some
instructions are performed out of sequence. Whatever happened, such problems with the
program are known as bugs.

Definition : Bugs are errors with a program that cause it to stop working or produce
incorrect or undesirable results.

18
It is the responsibility of the programmer to fix as many bugs in a program as present. To
find bugs effectively, a program should be tested with many test cases (called a test suite).
It is also a good idea to have others test one’s program because they may think up
situations or input data that one may never have thought of.

Definition : Debugging is the process of finding and fixing errors in program code.

Debugging is often a very time-consuming “chore” when it comes to being a


programmer. Involves fixing or resolving the errors (technically called bugs) identified
during testing. Testing and debugging should be repeated until all errors are fixed

1.2.7 Evaluating the Solution

Once the program produces what seems to be a correct result, it's essential to evaluate the
solution in the context of the original problem. Often, it becomes clear that the output
doesn’t fully solve the problem as expected, or additional steps are required. For
example, if the program generates a long list of numbers but the objective was to identify
patterns or features in the data, simply presenting the numbers may not be sufficient. In
such cases, the data might need to be visualized differently, such as through charts or
graphs, to better interpret the results.

During this process, the output may reveal that more data is needed or that the solution
needs to be optimized for efficiency, such as when a game runs too slowly. It's important
to remember that the computer will only follow the given instructions, so it's up to the
programmer to ensure the results align with the original problem. If the solution doesn’t
meet expectations, it may be necessary to go back and revisit earlier steps in the process,
even as far back as the initial problem definition, especially if any critical data was
missing.

This final evaluation step is crucial to ensure the program effectively addresses the
problem and meets the desired objectives. Evaluation criteria such as efficiency,
feasibility, and scalability should be defined and measured. Additionally, potential risks
related to the program’s deployment should be assessed. Collecting both quantitative and
qualitative feedback from stakeholders can guide further improvements to the program.

After incorporating any necessary changes, the refined code should undergo rigorous
testing. If the solution meets the required performance and correctness criteria, it can be
considered complete. However, if there are areas for improvement, the algorithm may
need to be redefined or the program optimized further to better fulfill the original
objectives.

19
1.3 ESSENTIALS OF PYTHON PROGRAMMING

1.3.1 Creating and using variables in Python

1. Character
The set of characters supported by a programming language is called character set. A
character can be an alphabet, a digit, or a special symbol. Python supports the following
characters:

●​ upper case alphabets (A–Z)


●​ lower case alphabets (a–z)
●​ digits (0–9)
●​ special symbols like @,#,%,$ etc.

Python maps each valid character to an integer value called ASCII value 'A' is 65

2. Constants
●​ A ‘constant’ is an entity whose value doesn’t change.

3. Variables

●​ A variable is a name that refers to a value.


●​ To simplify the retrieval and use of data values, these memory locations are given
names.

20
Naming rules for variables

1.​ Start with a letter or an underscore (_):

A variable name must begin with either a letter (a-z, A-Z) or an underscore ( _ ),
but not with a number.

●​ Valid: age, _name, var_1


●​ Invalid: 1age, 9name
2.​ Use letters, numbers, and underscores:

After the first character, you can use letters, numbers, or underscores.

●​ Valid: student_name, number_of_days_3


●​ Invalid: student-name, number@3
3.​ Case-sensitive:

Variable names are case-sensitive, meaning myVar and myvar are different.

●​ Valid: age and Age are two separate variables.


4.​ Cannot be a Python keyword:

You cannot use Python keywords (like if, for, while, etc.) as variable names.
These are reserved words in Python.

●​ Invalid: if, for, class

4. Keywords

●​ A keyword in Python is a reserved word that has a predefined meaning and


function within the language.
●​ Keywords are part of the Python syntax, and they cannot be used as variable
names, function names, or any other identifiers.
●​ All the keywords except True, False, and None are in lowercase, and they must be
written as is.
●​ Python has 29 keywords

21
1.3.2 Datatypes
●​ A data type in Python defines the kind of value a variable can hold and the
operations that can be performed on that value.
●​ Different data types in Python categorize data into specific types, such as
numbers, text, or more complex structures.

Key Characteristics:

●​ Defines the nature of the data: What type of data is being stored (e.g., text,
number, list).
●​ Determines operations: Each data type supports specific operations (e.g., you
can add numbers, but not strings and numbers directly).
●​ Python is dynamically typed: Python automatically detects the type based on the
assigned value.

Numeric datatype in python

The number or numeric data type is used to store numeric values. There are three distinct
numeric types

●​ integer
●​ float
●​ complex
1.​ Integer

The integers include numbers that do not have decimal points. The int datatype
supports integers ranging from −231 to 231 − 1.

Example: 10, - 42

2.​ Float
●​ Represent real numbers (with decimal points). float type supports from
−10308 to 10308 and has 16 digits of precision (number of digits after the
decimal point).
●​ A floating point number can be written using either ordinary decimal
notation or scientific notation. Scientific notation is often useful for
denoting numbers with very large or very small magnitudes.
●​ Example: 3.14, -0.001

22
3.​ Complex
●​ Complex numbers are written in the form x+yj, where x is the real part
and y is the imaginary part.

Example : 3+5j, 10j

4. Boolean

●​ int type has a subtype bool. Any variable of type bool can take one of the
two possible boolean values, True and False (internally represented as 1
and 0 respectively).

Example: is_student = True

String datatype in python

●​ A string literal or a string is a sequence of characters enclosed in a pair of


single quotes or double quotes.
●​ Multi-line strings are written within a pair of triple quotes, ``` or """.
●​ The strings ' ' and " " are called empty strings.

Key Characteristics of Strings

●​ Immutable: Once a string is created, it cannot be changed (although you


can create new strings based on it).
●​ Ordered: Strings can be indexed, meaning each character in the string has
a position (starting from 0).

Example

●​ greeting = "Hello, World!"


●​ name = 'Alice'
●​ multiline = '''This is a multiline string which
can have multiple lines of content line
string.'''
●​ Immutable example

23
String Operations:

1. String Concatenation

Combine (or concatenate) two or more strings using the + operator.

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2 ​ # Adds a space between the


words

print(result) ​​ ​ # Output: Hello World

2. Repetition:

The * operator allows you to repeat a string a specified number of times.

str1 = "Ha"

result = str1 * 3

print(result) # Output: HaHaHa

3. String Length

Use len() to find the length of a string.

str1 = "Hello, World!"

length = len(str1)

print(length) # Output: 13

4. Accessing Characters

Individual characters in a string can be accessed through indexing. Python follows


zero-based indexing, where the first character is located at index 0, the second at index 1,
and so on. Additionally, negative indices can be used to retrieve characters from the end
of the string.

24
5. Slicing

String slicing enables the extraction of a portion (or substring) from a string by defining a
range of indices.

The syntax for slicing follows this format: String[start:end:step]

Each part represents the following:

●​ start: The index where the slice begins (inclusive).


●​ end: The index where the slice ends (exclusive).
●​ step: Optional. Defines the step or stride between indices (default is 1).

25
Examples:

1. Basic Slicing:

●​ The slice starts at index 0 and ends at index 5 (but doesn’t include the character at
index 5).

text = "Hello, World!"


print(text[0:5]) # Output: Hello

2. Omitting the start or end:

●​ When start is omitted, slicing begins from the beginning of the string.
●​ When end is omitted, slicing goes till the end of the string.

text = "Hello, World!"


print(text[:5]) # Output: Hello
print(text[7:]) # Output: World!

3. Using a step

●​ A step can be specified to skip characters while slicing a string.

text = "Hello, World!"


print(text[::2]) # Output: Hlo ol!
4.Negative indices

You can use negative numbers to count from the end of the string.

text = "Hello, World!"


print(text[-6:]) #Output: World!
print(text[::-1]) #Output: !dlroW ,olleH (reverses
the string)

26
1.3.3 Using Math module
The math module in Python provides access to many mathematical functions and
constants. It allows you to perform various mathematical operations like finding the
square root, computing the factorial, trigonometric functions, logarithms, etc. To use a
function or a constant of the math module, you need to do two things:

1. import the module

import math

2. Access the function or the constant by prefixing its name with ”math.”(math
followed by a dot)

1. Mathematical Constants

●​ math.pi: Returns the value of π (pi), approximately 3.14159.


●​ math.e: Returns the value of Euler’s number e, approximately 2.71828.

2. Basic Functions

●​ math.sqrt(x): Returns the square root of x.


○​ print(math.sqrt(16))​ ​
○​ Output: 4.0
●​ math.pow(x, y): Returns x raised to the power y (i.e., x**y).
○​ print(math.pow(2, 3))​
○​ Output: 8.0
●​ math.factorial(x): Returns the factorial of x (only for non-negative integers).
○​ print(math.factorial(5)) ​
○​ Output: 120
●​ math.floor(x): Returns the largest integer less than or equal to x (rounds down).
○​ print(math.floor(4.7)) ​ ​
○​ Output: 4
●​ math.ceil(x): Returns the smallest integer greater than or equal to x (rounds up).
○​ print(math.ceil(4.3)) ​
○​ Output: 5
●​ math.fabs(x): Returns the absolute value of x as a float.
○​ print(math.fabs(-5.5)) ​
○​ Output: 5.5
●​ math.gcd(x, y): Returns the greatest common divisor of x and y.
○​ print(math.gcd(36,60)) ​

27
Output: 12

●​ math.trunc(x): Truncates x to the nearest integer toward zero.


○​ print(math.trunc(4.9)) ​ ​
○​ Output: 4
○​ print(math.trunc(-4.9))​ ​
○​ Output: -4

3. Trigonometric Functions

These functions assume angles are in radians unless otherwise stated.

●​ math.sin(x): Returns the sine of x (x is in radians).​


​ print(math.sin(math.pi/2))​
Output: 1.0
●​ math.cos(x): Returns the cosine of x (x is in radians).​
​ print(math.cos(math.pi)) ​
Output: -1.0
●​ math.tan(x): Returns the tangent of x (x is in radians).​
​ print(math.tan(math.pi/4))
Output: 1.0
●​ math.degrees(x): Converts angle x from radians to degrees.​
​ print(math.degrees(math.pi))
Output: 180.0
●​ math.radians(x): Converts angle x from degrees to radians.​
​ print(math.radians(180))
Output: 3.141592653589793 (π radians)

4. Exponential and Logarithmic Functions


●​ math.exp(x): Returns e raised to the power of x (where e ≈ 2.718).​
​ print(math.exp(1)) ​
Output: 2.718281828459045
●​ math.log(x): Returns the natural logarithm of x (base e).​
​ print(math.log(2.718281828459045))
Output: 1.0
●​ math.log10(x): Returns the base-10 logarithm of x.​
​ print(math.log10(100)) ​
Output: 2.0
●​ math.log2(x): Returns the base-2 logarithm of x.​
​ print(math.log2(8)) Output: 3.0

28
5. Hyperbolic Functions

These are analogous to the trigonometric functions but for hyperbolic sine, cosine, etc.

●​ math.sinh(x): Returns the hyperbolic sine of x.​


​ print(math.sinh(1)) ​ ​
Output: 1.1752011936438014
●​ math.cosh(x): Returns the hyperbolic cosine of x.​
​ print(math.cosh(1)) ​
Output: 1.5430806348152437
●​ math.tanh(x): Returns the hyperbolic tangent of x.​
​ print(math.tanh(1)) ​ ​
Output: 0.7615941559557649

6. Special Functions
●​ math.isqrt(x): Returns the integer square root of x (rounds down to the nearest
integer).​
​ print(math.isqrt(17))
Output: 4
●​ math.comb(n, k): Returns the number of ways to choose k items from n items
without repetition (n choose k).​
​ print(math.comb(5, 2))
Output: 10
●​ math.perm(n, k): Returns the number of ways to arrange k items from n items (n
permute k).​
​ print(math.perm(5, 2))
Output: 20

29
1.3.4 Using the Python Standard Library for handling basic I/O -
print, input

Handling basic I/O - print, input


1.​ Data input refers to collecting or retrieving data from external sources (like the
user or a file)
2.​ Data output refers to sending or saving data to external sources (like displaying
information on the screen or writing to a file).

1.3.4.1 input() Function in Python


The input() function in Python is used to take input from the user. It reads a line of text
from the user and returns it as a string. You can prompt the user with a message to make
the input more descriptive.

1. Basic Usage
To receive input from the user, which accepts the input as a string.

name = input("Enter your name: ")

print("Hello", name)

The input() function prompts the user to enter their name. Whatever the user types is
stored as a string in the variable name, and is then used in the print statement.

2. Reading Numeric Input

By default, the input() function returns the input as a string. If you want to take numeric
input (e.g., integers or floats), you need to explicitly convert the string to the appropriate
type using int() or float().

Example for integer input:


age = int(input("Enter your age: "))

print("You are ", age," years old.")

Example for float input:


height = float(input("Enter your height in meters: "))

print("Your height is ",height ," meters.")

30
3. Prompting Without a Message

If you don’t provide a prompt message, input() will just wait for the user to input
something:

user_input = input()

In this case, no message is shown to the user.

4. Multiple Inputs

To take multiple inputs, you can either use multiple input() calls or use splitting
techniques with a single input() call.

Example with multiple input() calls:


first_name = input("Enter your first name: ")

last_name = input("Enter your last name: ")

print("Hello",first_name,last_name,"!")

Example using split() to take multiple inputs in one line:

The split() function divides the input string into multiple parts based on spaces (or a
specified delimiter).

first_name, last_name = input("Enter your first and last


name: ").split()

print("Hello ", first_name,””,last_name,"!")

Summary:

●​ input() always returns a string.


●​ Convert user input to int, float, or other types as needed.
●​ Use split() for multiple inputs from a single line.

1.3.4.2 print( ) Function in Python


To display something on the screen, Python uses the method print. It just prints whatever
is given inside the quotes. See an example below:

31
print("Hello World!")
Output: Hello World!

Python prints as such, whatever is enclosed in " ". In the below example, the first
occurrence of a is within double quotes. So it is printed as such. The second a occurs
outside the quotes. Thus, its value 7 gets printed.
When commas are used within the print() function, a space is automatically inserted
between the string arguments, providing a simple way to concat

a = 7
print("The value of a is ",a)
Output: The value of a is 7

Another example - printing with expression

x=5
y=3
print("The value of ",x, "and",y,"is",x+y)
Output: The value of 5 and 3 is 8

String Concatenation
String concatenation using the print() function can be done by using the + operator inside
the print() function.

name="Ddddddd"
place="Kerala"
print("my name is "+name+" from "+place)
Output: my name is Ddddddd from Kerala

f-strings

(formatted string literals) are a way to format strings in Python, introduced in Python 3.6.
They allow you to embed expressions inside string literals, using curly braces {}. This
makes it easier and more readable to construct strings that include variable values.

Basic Syntax:

To create an f-string, prefix the string with the letter f or F. Inside the string, use curly
braces {} to include variables or expressions.

32
Examples of f-strings:
Example 1:
user_name = "Alice"
user_age = 30
print(f"Hello, my name is {user_name} and I am {user_age}
years old.")
Output: Hello, my name is Alice and I am 30 years old.

Example 2:
x=5
y=3
print(f"The value of {x} and {y} is {x+y}")
Output: The value of 5 and 3 is 8

Escape sequence

With the print method, whatever you enclose within a pair of double quotes, gets printed
as such. But there are a few exceptions, like quotation marks, commas, etc. For this
reason, Python provides special character constants referred to as escape sequences. An
escape sequence refers to a combination of characters beginning with a backslash (\)
followed by letters. Some of the escape sequences in Python are shown below

Escape Sequence Meaning


\b ​ - Backspace
\n ​ - Newline
\t ​ - Horizontal tab
\v ​ - Vertical tab
\\ ​ - The \ character
\'​ - Single quotation mark
\" ​ -Double quotation mark

Examples on Escape Sequence

1. print("Hello world")
Output: Hello world

2. print("Hello\tworld")

33
Output:Hello world

3. print("Hello\bworld")
Output:Hellworld

4. print("Hello \bworld")
Output:Helloworld

5. print("Hello\nworld")
Output:Hello
world
6. print("Hello\vworld")
Output:Hello
World

7. print("The teacher said, \"It\'s very easy to program


with Python\"")
Output:The teacher said, "It's very easy to program with
Python"

Programming examples

Program 6.1. To print “My first Python program”.


print("My first Python program")

Program 6.2. To input the user’s name and print a greeting message.
name=input("Enter your name")
print("Hello ",name)

Program 6.3. To input a number and display it.


num=int(input("Enter a number"))
print("The number you entered is",num)

Program 6.4. To add and subtract two input numbers.


a=int(input("Enter the first number"))
b=int(input("Enter the second number"))
sum=a+b
print("The sum of the two numbers is",sum)
difference=a-b
print("The difference between the two numbers
is",difference)

34
Program 6.5. To input the sides of a rectangle and find its perimeter.
length=int(input("Enter the length of the rectangle"))
breadth=int(input("Enter the breadth of the rectangle"))
perimeter=2*(length+breadth)
print("Perimeter of the rectangle is",perimeter)

Program 6.6. To input the side of a square and find its area.
side=int(input("Enter the side of the square"))
area=side**2
print("Area of the square is",area)

Program 6.7. To input the radius of a circle and find its circumference.
import math
radius=int(input("Enter the radius"))
c=2*math.pi*radius
print("Circumference of the circle is",c)

Program 6.8. To input two values a and b and then find ab.
import math
a=int(input("Enter the base"))
b=int(input("Enter the exponent"))
c=math.pow(a,b)
print(a,"to the power",b,"is",c)

Program 6.9. To input the base and altitude of a right triangle and find its
hypotenuse using Pythagoras theorem.
import math
b=int(input("Enter the base"))
a=int(input("Enter the altitude"))
temp=a**2+b**2
h=math.sqrt(temp)
print("The hypotenuse is",h)

Program 6.10. To input two values a and b and then swap them.
a=int(input("Enter a number"))
b=int(input("Enter another number"))
print("The numbers before swapping are a =",a,"and b =",b)
temp=a
a=b
b=temp

35
print("The numbers after swapping are a =",a,"and b =",b)

Program 6.11. To input two values a and b and then swap them without using a third
temporary variable
a=int(input("Enter a number"))
b=int(input("Enter another number"))
print("The numbers before swapping are a =",a,"and b =",b)
a=a+b
b=a-b
a=a-b
print("The numbers after swapping are a =",a,"and b =",b)

1.3.5 Introduction to Operators


Operators are special symbols or keywords that allow us to perform operations on
variables and values. These are essential for performing calculations, comparisons, and
logical operations in Python programs.
●​ OPERATORS: These are the special symbols. Eg- + , * , /, etc.
●​ OPERAND: It is the value on which the operator is applied.
Operators are classified into several categories:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators

●​ Arithmetic operators help perform mathematical operations such as addition,


subtraction, multiplication, and division.
●​ The remainder operator (%) requires both operands to be integers, and the second
operand is non-zero.
●​ The division operator (/) requires that the second operand be non-zero.
●​ The floor division operator (//) returns the floor value of the quotient of a division
operation. It is also called the Integer division.

36
Example
print(7.0//2)
Output: 3.0

print(7//2)
Output: 3

a = 10
b = 3
print(a + b)
print(a / b)
Output: ​ 13
3.3333
The precedence of Arithmetic Operators in Python is as follows:
1.​ Parentheses
2.​ Exponentiation
3.​ Multiplication/ Division (Multiplication and division have the same precedence)
4.​ Addition/ Subtraction(Addition and subtraction have the same precedence)

The modulus of Python operators helps us extract the last digit/s of a number. For
example:

●​ x % 10 -> yields the last digit


●​ x % 100 -> yield last two digits

37
2. Assignment Operators

●​ The assignment statement creates new variables and gives them values that can be
used in subsequent arithmetic expressions.
●​ The basic assignment is done with =, but there are several others that combine
assignment and arithmetic operations.
●​ Syntax: variable name = values
●​ Example: num1=10
●​ Compound assignment operators are +=, -=, *=, /=, //=, %=
●​ They are equivalent to below expressions

Examples:
a=10
b=5
print(a+b)
Output: 15

Python allows you to assign a single value to several variables simultaneously. An


example follows:
a=b=5
print(a,”\n”,b)
Output: 5
​ 5

You can also assign different values to multiple variables. See below
a,b,c=1,2.5,"ram"
print(a,b,c)
Output: 1 2.5 ram

Example of compound assignment operator


x = 5
x += 3 ​ # Equivalent to x = x + 3
print(x)
Outputs: 8

38
3. Comparison(Relational)Operators

●​ Comparison operators are used to compare two values and return a boolean result
(True or False).
●​ == and != are also known as equality operators.
●​ Comparison operators support chaining. For example, x < y <= z is equivalent to
x < y and y <= z.

The use of comparison operators is illustrated below:


Example
i,j,k=3,4,7
print(i>j)
Output: False

print((j+k)>(i+5))
Output: True

print(i == j)
Output: False

print(i!= j)
Output: True

Note:​ = is an assignment operator and == comparison operator.


Precedence of Comparison Operators
The comparison operators have lower precedence than the arithmetic operators. All the
operators within comparison operators have the same precedence order.

39
4. Logical Operators

●​ Logical operators perform Logical AND, Logical OR, and Logical NOT
operations. It is used to combine conditional statements. These are often used
with boolean values (True or False).
●​ Python includes three Boolean (logical) operators and , or , and not .
●​ Binary operator: The and operator and or operator expect two operands,which are
hence called binary operators.
○​ The and operator returns True if and only if both of its operands are True,
and returns False otherwise.
○​ The or operator returns False if and only if both of its operands are False,
and returns True otherwise.
●​ Unary operator: The not operator expects a single operand and is hence called a
unary operator.
●​ It returns the logical negation of the operand, that is, True, if the operand
is False, and
False if the operand is True.
●​ The behavior of each operator can be specified in a truth table for that operator.
The first row in the truth table contains labels for the operands and computed
expressions. Each row below the first row contains a possible combination of
values for the operands and the value resulting from applying the operator to
them. Table 1 shows the truth tables for or and and operators. Table 2 shows the
truth tables for not.

The use of logical operators is illustrated below:


Example 1
a = True
b = False
print(a and b)
Output: False
print(a or b)
Output: True

40
print(not a)
Output: False ​

Example 2
a=10
b=5
d=(a<b)and(a>0)
print(d)
Output:False
d=(a<b)or(a>0)
print(d)
Output: True
print(not a<b)
Output: True

Precedence of Logical Operators


The precedence of Logical Operators is as follows:
Logical not
Logical and
Logical or

5. Bitwise operators

●​ Bitwise operators take the binary representation of the operands and work on their
bits, one bit at a time.
●​ The bits of the operand(s) are compared starting with the rightmost bit - the least
significant bit, then moving towards the left and ending with the leftmost (most
significant) bit.
●​ The result of the comparison will depend on the compared bits and the operation
being performed.
●​ These bitwise operators can be divided into three general categories as discussed
below:

1.​ Logical bitwise operators


2.​ One’s complement operator
3.​ Bitwise shift operators

41
1. Logical bitwise operators

●​ There are three logical bitwise operators: bitwise and (&), bitwise exclusive or
(∧), and bitwise or ( | ). Each of these operators require two integer-type
operands.
●​ The operations are performed on each pair of corresponding bits of the operands
based on the following rules:
○​ A bitwise and expression will return 1 if both the operand bits are 1.
Otherwise, it will return 0.
○​ A bitwise or expression will return 1 if at least one of the operand bits is 1.
Otherwise, it will return 0.
○​ A bitwise exclusive or expression will return 1 if the bits are not alike (one
bit is 0 and the other is 1). Otherwise, it will return 0.
●​ These results are summarized in Table 5.5. In this table, b1 and b2 represent the
corresponding bits within the first and second operands, respectively.

2. One’s complement operator

●​ One’s complement is denoted by the symbol ∼. It operates by changing all zeros


to ones and ones to zeros in the binary representation of the operand.

3. Bitwise shift operators


●​ The two bitwise shift operators are shift left (<<) and shift right (>>).
●​ The expression x << n shifts each bit of the binary representation of x to the left, n
times. Each time we shift the bits left, the vacant bit position at the right end is
filled with a zero.
●​ The expression x >> n shifts each bit of the binary representation of x to the right,
n times. Each time we shift the bits right, the vacant bit position at the left end is
filled with a zero.

Binary Representation of 5 = 101


Right shifting once − 010 Binary Representation of 5 = 101
Right shifting twice − 001 Left shifting once − 1010

42
Left shifting twice − 10100 Left shifting thrice − 101000
Bitwise Operator table
Operator Description Exampl a=6 b=2
e

& Bitwise AND a&b 110


& → 010
010

| Bitwise OR a|b 110


| → 110
010

^ Bitwise XOR a^b 110


^ → 100
010

~ Bitwise NOT ~a 110 → 001

<< Left shift a<<2 110 → 11000

>> Right shift a>>2 110 → 001

Example:
a = 6 # Binary: 110
b = 2 # Binary: 010
print(a & b) # Outputs: 2 (Binary: 010)

Precedence of Bitwise Operators in Python

1.​ Bitwise NOT (high)


2.​ Bitwise Shift
3.​ Bitwise AND
4.​ Bitwise XOR
5.​ Bitwise OR (low)

5. Membership operator
●​ These operators test for the membership of a data item in a sequence, such as a
string.
●​ Two membership operators are used in Python.
●​ in– Evaluates to True if it finds the item in the specified sequence and False
otherwise.

43
●​ not in– Evaluates to True if it does not find the item in the specified sequence and
False otherwise.

Examples
'A' in 'ASCII'
Output: True
'a' in 'ASCII'
Output: False
'a' not in 'ASCII'
Output: True

6. Identity Operators
●​ is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located in the same part of the memory.
●​ x is y evaluates to true if and only if x and y are the same object.
●​ x is not y yields the inverse truth value.

Examples
a = 10
b = 20
c = 10
print(a is not b)
Output: True
print(a is c)
Output: True

Precedence and associativity of operators

When an expression contains more than one operator, in what order will the operations be
performed? To answer this question satisfactorily, one has to know the precedence of
operators. The order in which operators in an arithmetic expression are applied to their
respective operands is called the precedence of operators. It is also known by other
names, such as priority or hierarchy.
Operators with a higher precedence are applied before operators having a lower
precedence. For example, the multiplication operator has precedence over the addition

44
operator. This means that if an expression has both + and ∗, then addition will be
performed only after multiplication. The precedence of operators is shown in Table 5.6.
The operators are listed in groups in descending order; the upper group has higher
precedence than the lower ones.

We find that in Table 5.6, more than one operator exists in the same group. These
operators have the same precedence. If an expression has multiple operators with the
same precedence, the tie is resolved using associativity rules.

Associativity is of two types – Left to Right (L→ R) and Right to Left (R →L).
The third column of Table 5.6 lists the associativity of the operators. L→ R means that
when there are two operators with the same precedence, the operator that comes first on a
left-to-right scan of the expression will be given priority.
Similarly with R →L, the right operator has higher priority.

45
Consider the expression a − b + c. Since + and − are of the same precedence, so look for
associativity. The associativity is L→R. Thus − will be evaluated first as it comes to the
left.

Examples

Expression Evaluation Value


3+4*2 3+8 11
(3 + 4 ) * 2 7*2 14
2 ** 3 ** 2 2 ** 9 512
(2 ** 3) ** 2 8 ** 2 64
-3 ** 2 -(3 ** 2) -9
-(3) ** 2 (-3) ** 2 9
not True and False or (False and False) or True
True True

Example 1 Consider the assignment statement R = A + 3 < B ∗ 1 or C and D

Let the values of the variables be A = 1, B = 5, C = −1, andD = True. Figure 5.1 shows
the structure of the evaluation. The numbers shown in the circle denote the order in which
the various operators are applied. The final result is 1, which is assigned to R.

46
Mixed-Mode Arithmetic

Python supports mixed-mode arithmetic through type coercion, wherein the resultant of
an expression will have the most general data type among all operand data types
involved. The operand of a less general type will be temporarily and automatically
converted to the more general type before the operation is performed. The various
conversion rules are summarized in Table 5.9.

Table 5.9: Type coercion rules

Operands type Result type

int and int int

float and float float

int and float float

47
Performing calculations involving operands of different data types is called mixed-mode
arithmetic.

Consider computing the area of a circle having 3 unit radius:

print(3.14 * 3 ** 2)
Output: 28.26

Prepared By
Athithya Sadasakthi
Assistant Professor
Christ College of Engineering

48

You might also like