Module 1 - Algorithmic Thinking With Python
Module 1 - Algorithmic Thinking With Python
Module 1- Syllabus
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.
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.
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.
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.
● 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.
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.
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.
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.
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.
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.
Algorithm:
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
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
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:
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.
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:
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:
Assuming these assigned grade numbers are y1, y2, ⋯ , yn the following computational
model may be used:
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.
Consider the following example for solving the problem of Simple Interest. A flowchart
and pseudocode are given below
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.
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.
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.
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. 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:
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
20
Naming rules for variables
A variable name must begin with either a letter (a-z, A-Z) or an underscore ( _ ),
but not with a number.
After the first character, you can use letters, numbers, or underscores.
Variable names are case-sensitive, meaning myVar and myvar are different.
You cannot use Python keywords (like if, for, while, etc.) as variable names.
These are reserved words in Python.
4. 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.
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.
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
23
String Operations:
1. String Concatenation
str1 = "Hello"
str2 = "World"
2. Repetition:
str1 = "Ha"
result = str1 * 3
3. String Length
length = len(str1)
print(length) # Output: 13
4. Accessing Characters
24
5. Slicing
String slicing enables the extraction of a portion (or substring) from a string by defining a
range of indices.
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).
● When start is omitted, slicing begins from the beginning of the string.
● When end is omitted, slicing goes till the end of the string.
3. Using a step
You can use negative numbers to count from the end of 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:
import math
2. Access the function or the constant by prefixing its name with ”math.”(math
followed by a dot)
1. Mathematical Constants
2. Basic Functions
27
Output: 12
3. Trigonometric Functions
28
5. Hyperbolic Functions
These are analogous to the trigonometric functions but for hyperbolic sine, cosine, etc.
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
1. Basic Usage
To receive input from the user, which accepts the input as a string.
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.
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().
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()
4. Multiple Inputs
To take multiple inputs, you can either use multiple input() calls or use splitting
techniques with a single input() call.
print("Hello",first_name,last_name,"!")
The split() function divides the input string into multiple parts based on spaces (or a
specified delimiter).
Summary:
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
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
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
Programming examples
Program 6.2. To input the user’s name and print a greeting message.
name=input("Enter your name")
print("Hello ",name)
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. Arithmetic Operators
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:
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
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
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.
print((j+k)>(i+5))
Output: True
print(i == j)
Output: False
print(i!= j)
Output: True
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.
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
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:
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.
42
Left shifting twice − 10100 Left shifting thrice − 101000
Bitwise Operator table
Operator Description Exampl a=6 b=2
e
Example:
a = 6 # Binary: 110
b = 2 # Binary: 010
print(a & b) # Outputs: 2 (Binary: 010)
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
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
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.
47
Performing calculations involving operands of different data types is called mixed-mode
arithmetic.
print(3.14 * 3 ** 2)
Output: 28.26
Prepared By
Athithya Sadasakthi
Assistant Professor
Christ College of Engineering
48