0% found this document useful (0 votes)
11 views

S1_ATP_Module_1

The document outlines a course on Algorithmic Thinking with Python, focusing on problem-solving strategies, the problem-solving process, and essentials of Python programming. It details various problem-solving strategies including trial and error, heuristics, means-ends analysis, and algorithmic approaches, emphasizing the importance of adaptability and critical thinking. Additionally, it describes the structured process of solving problems using computers, including understanding the problem, formulating models, developing algorithms, coding, testing, and evaluating solutions.

Uploaded by

keerthanaer05
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 views

S1_ATP_Module_1

The document outlines a course on Algorithmic Thinking with Python, focusing on problem-solving strategies, the problem-solving process, and essentials of Python programming. It details various problem-solving strategies including trial and error, heuristics, means-ends analysis, and algorithmic approaches, emphasizing the importance of adaptability and critical thinking. Additionally, it describes the structured process of solving problems using computers, including understanding the problem, formulating models, developing algorithms, coding, testing, and evaluating solutions.

Uploaded by

keerthanaer05
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/ 34

ALGORITHMIC THINKING WITH

PYTHON

Course Code: UCEST105

MODULE I:
Reference:
Ajeesh Ramanujan, Narasimhan T, ALGORITHMIC THINKING WITH PYTHON

SYLLABUS Contact Hours 7 Hrs.

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

Problem-solving strategies are essential tools that enable you to effectively tackle a wide range of
challenges by providing structured methods to analyze, under stand, and resolve problems. These
strategies include systematic approaches such as Trial and Error, Heuristics, Means-Ends
Analysis, and Backtracking, each offering unique benefits and applications. Understanding
multiple problem solving strategies is crucial as it allows for adaptability and flexibility, ensuring
that one can choose the most efficient method for any given situation. This versatility enhances
problem-solving efficiency and improves outcomes by offering diverse perspectives and
potential solutions. Additionally, employing various strategies enriches cognitive skill
development, critical thinking, and creativity. By integrating these strategies into everyday
problem-solving, you can approach challenges with confidence and resilience, ultimately
achieving more successful and innovative solutions.

1.1 Importance of Understanding Multiple Problem-Solving Strategies


Understanding multiple problem-solving strategies is crucial because it equips individuals with a
diverse toolkit to tackle a variety of challenges. Different problems often require different
approaches, and being familiar with multiple strategies allows for greater flexibility and
adaptability. For example, some problems might be best solved through a systematic trial and
error method, while others might benefit from a more analytical approach like means-ends
analysis. By knowing several strategies, one can quickly switch tactics when one method does
not work, increasing the chances of finding a successful solution.

Additionally, having a collection of problem-solving strategies enhances critical thinking and


creativity. It encourages thinking outside the box and considering multiple perspectives, which
can lead to more innovative and effective solutions. This broad understanding also helps in
recognizing patterns and similarities between different problems, making it easier to apply
previous knowledge to new situations. In both academic and real-world scenarios, this versatility
not only improves problem-solving efficiency but also boosts confidence and competence in
facing various challenges. Some benefits are as follows:

 Adaptability: Different problems require different approaches. Under standing multiple


strategies allows for flexibility and adaptability in problem solving.

2
 Efficiency: Some strategies are more effective for specific types of problems. Having a
repertoire of strategies can save time and resources.
 Improved Outcomes: Diverse strategies offer multiple perspectives and potential solutions,
increasing the likelihood of finding optimal solutions.
 Skill Development: Exposure to various strategies enhances cognitive skills, critical
thinking, and creativity.
Let us look at some commonly used problem-solving strategies

1.2 Trial And Error Problem-Solving Strategy


The trial-and-error problem-solving strategy involves attempting different solutions and learning
from mistakes until a successful outcome is achieved. It is a fundamental method that relies on
experimentation and iteration, rather than systematic or analytical approaches.

Consider the situation where you have forgotten the password to your online account, and there
is no password recovery option available. You decide to use trial and error to regain access:

1) Initial Attempts: You start by trying passwords you commonly use. For instance, you might
first try ”password123,” ”Qwerty2024,” or ”MyDogTommy”.
2) Learning from Mistakes: None of these initial attempts work. You then recall that you
sometimes use a combination of personal information. You try variations incorporating your
birthdate, pet’s name, or favorite sports team.
3) Refinement: After several failed attempts, you remember you recently started using a new
format for your passwords, combining a favorite quote with special characters. You
attempted various combinations, such as”ToBeOrNotToBe!”, ”NeeNeeyaayirikkuka#,” and
other combinations.
4) Success: Eventually, through persistent trial and error, you hit upon the correct
password: ”NeeNeeyaayirikkuka#2024.”

In this scenario, trial and error involved systematically trying different potential passwords,
learning from each failed attempt, and refining the approach based on what you remember about
your password habits. This method is practical when there is no clear pathway to the solution and
allows for discovering the correct answer through persistence and adaptability.

3
1.3 Algorithmic Problem-Solving Strategy

An algorithm is a step-by-step, logical procedure that guarantees a solution to a problem. It is


systematic and follows a defined sequence of operations, ensuring consistency and accuracy in
finding the correct solution.
When baking a cake, you follow a precise recipe, which acts as an algorithm:

1) Gather Ingredients: Measure out 2 cups of flour, 1 cup of sugar, 2 eggs, cup of butter, 1
teaspoon of baking powder, and 1 cup of milk.
2) Preheat Oven: Set the oven to 175°C.
3) Mix Ingredients: In a bowl, combine the flour, baking powder, and sugar. In another bowl,
beat the eggs and then mix in the butter and milk. Gradually combine the wet and dry ingredients,
stirring until smooth.
4) Prepare Baking Pan: Grease a baking pan with butter or cooking spray
5) Pour Batter: Pour the batter into the prepared pan.
6) Bake: Place the pan in the preheated oven and bake for 30-35 minutes.
7) Check for Doneness: Insert a toothpick into the center of the cake. If it comes out clean, the
cake is done.
8) Cool and Serve: Let the cake cool before serving.

By following this algorithm (the recipe), you systematically achieve the desired
result — a perfectly baked cake.

1.4. Heuristic Problem-Solving Strategy

A heuristic is a practical approach to problem-solving based on experience and intuition. It does


not guarantee a perfect solution but provides a good enough solution quickly, often through rules
of thumb or educated guesses. When driving in a city with frequent traffic congestion, you might
use a heuristic approach to find the fastest route to your destination:

1) Rule of Thumb: You know from experience that certain streets are typically less congested
during rush hour.
2) Current Conditions: You use a traffic app to check current traffic conditions, looking for
red or yellow indicators on major roads.
3) Alternative Routes: You consider side streets and shortcuts you have used before that tend
to be less busy.

4
4) Decision: Based on the app and your knowledge, you decide to avoid the main highway
(which shows heavy congestion) and take a series of back roads that usually have lighter
traffic.

While this heuristic approach does not guarantee that you will find the absolute fastest route, it
combines your experience and real-time data to make an informed, efficient decision, likely
saving you time compared to blindly following the main routes.

1.5 Means-Ends Analysis Problem-Solving Strategy

Means-ends analysis is a strategy that involves breaking down a problem into smaller,
manageable parts (means) and addressing each part to achieve the final goal (ends). It involves
identifying the current state, the desired end state, and the steps needed to bridge the gap between
the two.

Imagine you want to plan a road trip from Trivandrum to Kashmir. Here is how you might use
means-ends analysis:
1. Define the Goal: Your ultimate goal is to drive from Trivandrum to Kashmir.
2. Analyze the Current State: You start in Trivandrum with your car ready to go.
3. Identify the Differences: The primary difference is the distance between Trivandrum and
Kashmir, which is approximately 3,700 kilometers.
4. Set Sub-Goals (Means):
a) Fuel and Rest Stops: Determine where you will need to stop for fuel and rest.
b) Daily Driving Targets: Break the trip into daily segments, such
as driving 500-600 kilometers per day.
c) Route Planning: Choose the most efficient and scenic route, considering highways,
weather conditions, and places you want to visit.
5. Implement the Plan:
a) Day 1: Drive from Trivandrum to Bangalore, Karnataka (approx. 720 km). Refuel in
Madurai, Tamil Nadu. Overnight stay in Bangalore.
b) Day 2: Drive from Bangalore to Hyderabad, Telangana (approx. 570 km). Refuel in
Anantapur, Andhra Pradesh. Overnight stay in Hyderabad.
c) Day 3: Drive from Hyderabad to Nagpur, Maharashtra (approx. 500 km). Refuel in
Adilabad, Telangana. Overnight stay in Nagpur.

5
d) Day 4: Drive from Nagpur to Jhansi, Uttar Pradesh (approx. 580 km). Refuel in Sagar,
Madhya Pradesh. Overnight stay in Jhansi.
e) Day 5: Drive from Jhansi to Agra, Uttar Pradesh (approx. 290 km). Refuel in Gwalior,
Madhya Pradesh. Overnight stay in Agra. Visit the Taj Mahal.
f) Day 6: Drive from Agra to Chandigarh (approx. 450 km). Refuel in Karnal, Haryana.
Overnight stay in Chandigarh.
g) Day 7: Drive from Chandigarh to Jammu (approx. 350 km). Refuel in Pathankot,
Punjab. Overnight stay in Jammu.
h) Day 8: Drive from Jammu to Srinagar, Kashmir (approx. 270 km).
6. Adjust as Needed: Throughout the trip, you may need to make adjust ments based on
traffic, road conditions, or personal preferences.

By breaking down the long journey into smaller, achievable segments and addressing each part
systematically, you can effectively plan and complete the road trip. This method ensures that you
stay on track and make steady progress to ward your final destination, despite the complexity
and distance of the trip.

1.6. Problem decomposition


In the previous example of traveling from Trivandrum to Kashmir, breaking down the journey
into smaller segments helped you come up with an effective plan for the completion of the trip.
This is the key to solving complex problems. When the problem to be solved is too complex to
manage, break it into manageable parts known as sub-problems. This process is known as
problem decomposition. Here are the steps in solving a problem using the decomposition
approach:

1. Understand the problem: Develop a thorough understanding of the problem.


2. Identify the sub-problems: Decompose the problems into smaller parts.
3. Solving the sub-problems: Once decomposition is done, you proceed to solve the
individual sub-problems. You may have to decide upon the order in which the various sub-
problems are to be solved.
4. Combine the solution: Once all the sub-problems have been solved, you should combine all
those solutions to form the solution for the original problem.
5. Test the combined solution: Finally you ensure that the combined solution indeed solves
the problem effectively.

6
2. Algorithmic problem solving with computers

In today’s digital era, the computer has become an indispensable part of our life. Down from
performing simple arithmetic right up to accurately determining the position for a soft lunar
landing, we rely heavily on computers and allied digital devices. Computers are potent tools for
solving problems across diverse disciplines. Problem-solving is a systematic way to arrive at
solutions for a given problem.

2.1 The Problem solving process


1. Understand the problem: Effective problem-solving demands a thorough knowledge of the
problem domain. Once you have identified the problem, its exact nature must be sought and
defined. The problem context, objectives, and constraints if any are to be understood
properly. Several techniques can be used to gather information about a problem. Some of
these include conducting interviews and sending questionnaires to the stakeholders (people
who are concerned with the problem). Segmenting a big problem into simple manageable
ones often helps you to develop a clear picture of the problem.
2. Formulate a model for the solution: After the problem is thoroughly understood, the next
step is to devise a solution. You should now identify the various ways to solve the problem.
Brainstorming is one of the most commonly used techniques for generating a large number
of ideas within a short time. Brainwriting and Mind mapping are two alternative techniques
that you can employ here. The generated ideas are then transformed into a conceptual model
that can be easily converted to a solution. Mathematical modeling and simulation modeling
are two popular modeling techniques that you could adopt. Whatever the modeling technique
is, ensure the defined model accurately reflects the conceived ideas.
3. Develop an algorithm: Once a list of possible solutions is determined, they have to be
translated into formal representations – algorithms. Obviously, you do not implement all the
solutions. So the next step is to assess the pros and cons of each algorithm to select the best
one for the problem. The assessment is based on considering various factors such as memory,
time, and lines of code.
4. Code the algorithm: The interesting part of the process! Coding! After the best algorithm is
determined, you implement it as an executable program. The program or the code is a set of
instructions that is more or less, a concrete representation of the algorithm in some
programming language. While coding, always follow the incremental paradigm – start with
the essential functionalities and gradually add more and more to it.

7
5. Test the program: Nobody is perfect! Once you are done with the coding, you have to
inspect your code to verify its correctness. This is formally 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. You
can get the help of automated testing tools to generate a test suite for your code. Closely
associated with testing is the process of debugging which involves fixing or resolving the
errors (technically called bugs) identified during testing. Testing and debugging should be
repeated until all errors are fixed.
6. Evaluate the solution: This final step is crucial to ensure that the program effectively
addresses the problem and attains the desired objectives. You have to first define the
evaluation criteria. These could include metrics like efficiency, feasibility, and scalability, a
few to mention. The potential risks that could arise with the program’s deployment are also
to be assessed. Collect quantitative and qualitative feedback from the stake holders. Based
on the feedback, you have to work on making necessary improvements to the program.
Nevertheless, the refined code should also be subject to rigorous testing.

2.1 A case study - The Discriminant calculator


Problem-solving process to determining the discriminant of a quadratic equation.
1. Understand the problem: Here we formally define the problem by specifying the inputs
and output.
Input: The three coefficients a, b and c of the quadratic equation
Output: The discriminant value D for the quadratic equation
2. Formulate a model for the solution: Develop a mathematical model for the solution, that is
identify the mathematical expression for the quadratic equation discriminant D:
D = b 2 − 4ac
3. Develop an algorithm: A possible algorithm (actually, a pseudocode) for our discriminant
problem is given below:
1. Start
2. Read(a, b, c)
3. d=b∗ b−4∗ a∗ c
4. Print(d)
5. Stop
8
4. Code the algorithm: The Python program to calculate the discriminant is as follows

#Input the coefficients


a = int(input("Enter the value of first coefficient"))
b = int(input("Enter the value of second
coefficient"))
c = int(input("Enter the value of third coefficient"))
#Find the discriminant
d = (b**2) - (4*a*c)
#Print the discriminant
print(d)

5. Test the program: You create a test suite similar to the one shown in Table 1.2. Each row
denotes a set of inputs (a, b, and c) and the expected output (d) with which the actual output is to
be comp

Table 1: A test suite for the discriminant calculator

Sl. No. a b c d
1 10 2 5 -196
2 5 7 1 29
3 2 4 2 0
4 1 1 1 -3
5 3 2 5 -56
6 2 8 2 48

2.2 Exercises

1. A bear, starting from the point P, walked one mile due south. Then he changed direction and
walked one mile due east. Then he turned again to the left and walked one mile due north,
and arrived at the point P he started from. What was the color of the bear?
2. Two towns A and B are 3 kilometers apart. It is proposed to build a new school serving 100
students in town A and 50 students in town B. How far from town A should the school be
built if the total distance travelled by all 150 students is to be as small as possible?
3. A traveller arrives at an inn. He has no money but only a silver chain consisting of 6 links.
He uses one link to pay for each day spent at the inn, but the innkeeper agrees to accept no

9
more than one broken link. How should the traveller cut up the chain in order to settle
accounts with the innkeeper on a daily basis?
4. What is the least number of links that have to be cut if the traveller stays 100 days at the inn
and has a chain consisting of 100 links? What is the answer in the general case (n days and
n links)?
5. The minute and hour hands of a clock coincide exactly at 12 o’clock. At what time later do
they first coincide again?
6. Six glasses are in a row, the first three full of juice, the second three empty. By moving only
one glass, can you arrange them so that empty and full glasses alternate?
7. You throw away the outside and cook the inside. Then you eat the outside and throw away
the inside. What did you eat?
8. Rearrange the letters in the words new door to make one word.
9. A mad scientist wishes to make a chain out of plutonium and lead pieces. There is a problem,
however. If the scientist places two pieces of plutonium next to each other, BOOM! The
question is, in how many ways can the scientist safely construct a chain of length n?
10. Among 12 ball bearings, one is defective, but it is not known if it is heavier or lighter than
the rest. Using a traditional balance (with two pans hanging down the opposite ends of a
lever supported in the middle), how do you determine which is the defective ball bearing,
and whether it is heavier or lighter than the others, within three attempts?

10
3. ESSENTIALS OF PYTHON PROGRAMMING
3.1. Creating and using variables in Python
A variable is a named memory location in which we can store values for the particular program.
In other words, Variable is a name which is used to refer memory location. Variable also known
as identifier and used to hold value. In Python, We don't need to declare explicitly variable in
Python. When we assign any value to the variable that variable is declared automatically. In
Python, We don't need to specify the type of variable because Python is a loosely typed language.
In loosely typed language no need to specify the type of variable because the variable
automatically changes it's data type based on assigned value.
3.1.1 Rules for naming variable:
Variable names can be a group of both letters and digits, but they have to begin with a letter or an
underscore.It is recommended to use lowercase letters for variable name. ‘SUM’ and ‘sum’ both
are two different variables.

Example 1:
a=10 # integer
b=12.5 # float
b="StudyGlance" # string
Python allows us to assign a value to multiple variables and
multiple values to multiple variables in a single statement which is also known as multiple
assignment.
Assign single value to multiple variables :

Example 2:
x = y = z = 50

Assign multiple values to multiple variables :

Example 3:
a, b, c = 5, 10, 15

11
3.2. Numeric and String data types in Python
In general, Data Types specifies what type of data will be stored in variables. Variables can hold
values of different data types.Python is a dynamically typed or loosely typed language, hence we
need not define the type of the variable while declaring it.The interpreter implicitly binds the
value with its type.Python provides us the type () function which enables us to check the type of
the variable.
Python provides following standard data types, those are:
1. Numbers
2. String

3.2.1. Numbers:
Number stores numeric values. Python creates Number type variable when a number is assigned
to a variable.
There are three numeric types in Python:
1. Int
2. float
3. complex

3.2.1.1. int:
int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example 4:
a = 10
b = -12
c = 123456789

3.2.1.2. float:
Float or "floating point number" is a number, positive or negative, containing one or more
decimals.

Example 5:
x = 1.0
y = 12.3
z = -13.4

12
3.2.1.3. complex:
Complex numbers are written with a "j" as the imaginary part.

Example 6:
A = 2+5j
B = -3+4j
C = -6j

3.2.1.4. String:
The string can be defined as the sequence of characters represented in the quotation marks. In
python, we can use single, double, or triple quotes to define a string. In the case of string
handling, the operator + is used to concatenate two strings as the operation "hello"+" python"
returns "hello python".

Example 7:
S1=‘Welcome’ #using single quotes
S2=“To” #using double quotes
S3=‘’’Python’’’ #using triple quotes

Example 8: Python programme


a = 10
b = “Python"
c = 10.5
d = 2.14j
print("Data type of Variable a :", type(a))
print("Data type of Variable b :", type(b))
print("Data type of Variable c :", type(c))
print("Data type of Variable d :", type(d))

13
Output of the programme:
Datatype of Variable a : <class ‘int’>
Datatype of Variable b : <class ‘str’>
Datatype of Variable c : <class ‘float’>
Datatype of Variable d : <class ‘complex’>

3.3. Using the math module


Python provides many functions ranging from input/output to performing complex calculations.
Python groups together functions providing similar functionalities into a module for easy access
to them. This module includes several functions that perform basic mathematical operations -
sqrt(), sin(), exp(), a few to mention.
Many programs are created to solve mathematical problems.Some of the most popular
mathematical functions are defined in the Python math module. These include trigonometric
functions, representation functions, logarithmic functions, angle conversion functions, etc.In
addition, two mathematical constants (pi and e) are also defined in this module. The Python math
module provides the mathematical functions.

To use a function or a constant of the math module, you need to do two things:
1. import the module
2. access the function or the constant by prefixing its name with ”math.” (math followed
by a dot)

To use functions in a module, you have to import it first as the following syntax:

import module_name

For example, we have to import the math module before using its functions or constants :

>>> import math


>>> math.pi # pi is a constant
3.141592653589793
>>> math.cos(5.89) # cos is a function
0.92369335287311

14
3.4. Using the Python Standard Library for handling basic I/O
Python provides various functions or methods for performing I/O operations. A function is a
named block of statements that carries out some specific, well-defined task. A program can be
seen as a collection of functions, each of which serves a unique purpose. Functions are of two
types: built-in and user-defined functions. Built-in functions are those that are provided by the
interpreter itself. These include I/O functions, mathematical functions, etc. User-defined
functions are those that are created by the programmers. Optionally a function can take input
values called parameters or arguments to process and could also give back an output value,
which is known as return value

3.4.1. Print

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

>>> print("Hello World!")


Hello World!

See another example now: Consider the statements

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

Python prints as such, whatever is enclosed in " ". In the above 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. See another
example:

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

15
Python f-strings offer a prettier way to achieve the same message output. See below:

>>> print(f " The value of {x} and {y} is {x+y}")


The value of 5 and 3 is 8

As shown above, the string to be printed should be prefixed with a ‘f ’ indicating an f - string.
The variables to be printed are to be enclosed in a pair of braces.

To receive input from the user, Python provides the input() method which accepts the input as a
string. See an example:

>>> myName = input(" What is your name? ")


What is your name? Python language
>>> print("I am ", myName)
I am Python language

3.4.2. Input
input() can accept numbers too but are accepted as strings. So if any arithmetic operation is to be
performed on the received input, the programmer must convert them from strings to the
appropriate numeric types. Python uses type conversion functions to convert values from one
data type to another.
The type conversion functions have the same name as the data type to which it converts. Table.1
lists the various type conversion functions. Note that the int function converts a float to an int by
truncation, not by rounding to the nearest whole number. Truncation simply chops off the
number’s fractional part.

Python provides a function type() to know the data type of a variable. See below

16
>>> i =2
>>> b =True
>>> s ="Hello"
>>> f =7.18
>>> print(type(i))
<class 'int'>
>>> print(type(b))
< class ' bool' >
>>> print(type(s))
<class 'str'>
>>> print(type(f))
<class 'float'>

Table. 1: Type conversion functions

Conversion Function Sample usage Value Returned


int(a number or a string) int(3.7) 3
int('347') 347
float(a number or a string) float(33) 33.0
float('33.8') 33.8
str(any value) str(37) ‘37’
str(37.6) '37.6’

3.4.3. Escape sequences


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 in Table.2.

3.4.4. Program Comments and Docstrings


As programs get bigger and more complicated, they get more difficult to read and understand.
For this reason, it is beneficial to add notes to your programs to explain the purpose of the
statements. These notes are called comments. A comment is a piece of program text that the
computer ignores but provides useful documentation to programmers. These comments begin
with the # symbol and extend to the end of a line. Everything from the # to the end of the line is

17
ignored by the interpreter while execution – it does not affect the program.

An end-of-line comment might explain the purpose of a variable. Here is an


example:

>>> sum = 5 + 7 # the variable sum contains the sum of 5 and 7

You can also put comments on a separate line:

>>> # Let us now print Hello


>>> print("Hello")
Hello

Python also supports comments that extend multiple lines, one way of doing it is to use # in the
beginning of each line. Here is an example:

>>> # This is a long comment


>>> # and it extends
>>> # to multiple line

Just as comments are attached to individual statements, you can also include details about the
program’s purpose at the beginning of the program file. This type of comment called a docstring,
is a multi-line string. Here is an example:

"""
Program name: areaRect.py
Version: 1.1
This program finds the area of a rectangle.
The inputs are two integers representing the length
and breadth of a rectangle, and the output is an
integer named area that represents the area of
the rectangle
"""

18
Table.2: Escape sequences in Python

Escape Sequence Meaning


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

3.4.5. Programming examples


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

print("My first Python program")

Program 2. To input the user’s name and print a greeting message.

name=input("Enter your name")


print("Hello ",name)

Program 3. To input a number and display it.

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

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

19
Program 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. 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 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 8. To input two values a and b and then find a b .

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)

20
Program 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 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
print("The numbers after swapping are a =",a,"and b =",b)

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

21
3.5. Python operators and their precedence

3.5.1. Introduction
An arithmetic expression comprises operands and operators. Operands represent data items on
which various operations are performed. The operations are denoted by operators. The operands
can be constants or variables. When a variable name appears in the place of an operand, it is
replaced with its value before the operation is performed. The operands acted upon by arithmetic
operators, must represent numeric values. Thus, the operands can be integer quantities, floating-
point quantities, or even characters (recall that every character has an equivalent ASCII value).
3.5.2. Operators in Python
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators• Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
3.5.2.1. Arithmetic Operators
The various arithmetic operators in Python are tabulated in Table 3.1. The remainder operator (%)
requires both operands to be integers, and the second operand is non-zero. Similarly, 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. See the example below:

>>> 7.0//2
3.0
>>> 7//2
3

Floor division is also called integer division.

22
Table 3.1: Arithmetic operators
Operation Operator
Negation -
Addition +
Subtraction -
Multiplication *
Division /
Floor division //
Remainder %
Exponentiation **

3.5.2.2. Assignment operator


‘=’ is the assignment operator. The assignment statement creates new variables and gives them
values that can be used in subsequent arithmetic expressions. See the example:

>>> a=10
>>> b=5
>>> a+b
15

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


An example follows:

>>> a=b=5
>>> a
5
>>> b
5

You can also assign different values to multiple variables. See below

23
>>> a,b,c=1,2.5,"ram"
>>> a
1
>>> b
2.5
>>> c
'ram'

Python supports the following six additional assignment operators (called compound assignment
operators): +=, -=, *=, /=, //= and %=. These are described below:

Expression Equivalent to Table 3.2: Comparison operators

a+=b a=a+b Operation Operator

a-=b a=a-b Equal to ==

a*=b a=a*b Not equal to !=

a/=b a=a/b Greater than >

a//=b a=a//b Greater than or equal to >=

a%=b a=a%b Less than <


Less than or equal to <

3.5.2.3. Comparison Operators


Table 3.2 shows the various comparison operators. Comparison operators are also called
relational operators. The result of a comparison is either True or False. == and != are also known
as equality operators. The use of comparison operators is illustrated below:

>>> i,j,k=3,4,7
>>> i>j
False
>>> (j+k)>(i+5)
True

Comparison operators support chaining. For example, x < y <= z is equivalent to x < y and
y <= z.

24
3.5.2.4. Logical Operators
Python includes three Boolean (logical) operators viz. and , or , and not . 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. 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 behaviour 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. Tables 3.3 shows the truth tables for or and and operators. Table
3.4 shows the truth tables for not.

Table 3.3: Truth tables for logical OR and


logical AND operators Table 3.4: Truth table
A b a or b a and b for logical NOT
False False False False a not a
False True True False False True
True False True False True False
True True True True

In the context of logical operators, Python interprets all non-zero values as True and zero as False.
See examples below:

>>> 7 and 1
1
>>> -2 or 0
-2
>>> -100 and 0
0

25
3.5.2.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:
One’s complement operator
One’s complement is denoted by the symbol ∼ . It operates by changing all
zeroes to ones and ones to zeroes in the binary representation of the operand.
The operand must be an integer-type quantity.
Example 5.1. This example illustrates the one’s complement operator. See
below:

>>> ~98
-99
>>> ~102
-103

Let us understand the results obtained. Take 102. Its binary is 01100110.
Flipping the bits, yields 10011001 = -103. This is shown below:

102 = 0110 0110


∼ 102 = 1001 1001
= -103
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.

26
 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 3.5. In this table, b1 and b2 represent the corresponding
bits within the first and second operands, respectively

Table 3.5: Logical bitwise operators


b1 b2 b1 & b2 b1 | b2 b1 ^ b2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Example 5.2. This example illustrates the operation of the three logical bitwise operators as
shown below:

>>> a=20
>>> b=108
>>> a&b
4
>>> a|b
124
>>> a^b
120

27
The following justifies these results.

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.

Example 5.3. This example illustrates the bitwise shift operators as shown below:

>>> 120>>2
30
>>> 10<<3
80

28
Membership Operators

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.
 not in – Evaluates to True if it does not find the item in the specified sequence and False
otherwise.

See the examples below:

>>> 'A' in 'ASCII'


True
>>> 'a' in 'ASCII'
False
>>> 'a' not in 'ASCII'
True

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.

29
3.6. 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

Table 3.6: Precedence rules in Python

precedence. For example, the multiplication operator has precedence over the addition 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.

30
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

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.

Figure 3.1: Evaluation of an arithmetic expression

31
Mixed-Mode Arithmetic

Table 3.9: Type coercion rules

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.

32
In the above example, the value 9 (result of 3 ** 2) is converted to 9.0 before the multiplication.

Note:-
When we group a set of values, variables, operators or function calls that turn out as an
expression. And once you execute that expression, Python interpreter evaluates it as a valid
expression.
See a simple example given below.

>>> 3 + 4
7

Here, the ‘3 + 4’ is a Python expression. It contains one operator and two operands. However, a
more complex statement can include multiple operators.

Exercises
1. Write a Python program to calculate simple interest by inputting the value of the Principal
amount, period, and interest rate from the user.
2. Write a Python program to convert the time input in minutes to hours and minutes. For
example, 85 minutes is 1 hour 25 minutes.
3. Write a Python program that inputs the cost of an item and the number of items and displays
the total cost.
4. Write a Python program that takes an amount in dollars and converts it to Indian rupees.
5. Write a Python program to reverse a three-digit number.
6. You are given the task of calculating the electricity bill of a house. Each house has the
following components: fan, light, washing machine, and computer. Each fan consumes 1
unit per day, and each light consumes 0.5 units per day, the washing machine consumes 2
units per day and each computer consumes 3 units per day. Let the cost of 1 unit be 50
rupees. Input the number of fans, lights, washing machines, and computers for a particular
house and find the total electricity bill for that house for 2 months. Assume a 30-day month.

33
Exercises
1. Perform the following operations:
(a) 15 and -8
(b) 127 or 0
(c) 0 and 1048
(d) not 10787
2. Perform the following operations:
(a) 12 & 10
(b) 55 & 24
(c) 45 | 50
(d) 13 | 99
(e) 18 ∧ 20
(f) 118 ∧ 65
(g) ∼ 50
(h) 14 << 3
(i) 25 << 2
(j) 15 >> 4
(k) 45 >> 3
3. Evaluate the following expressions:
(a) 34 ** 2 * 8 + -8
(b) 2 ** 3 ** 4
(c) (3 * 22) + - 8 ** 2 + 25
(d) True and not False or not True and True
(e) 45 * 2 + - 75 and 0 ** 4 or 3

34

You might also like