Python Module 1 Complete Notes
Python Module 1 Complete Notes
MODULE 1
SYLLABUS MODULE 1 PART 1
PROBLEM SOLVING
STEPS:
process the problem lies and avoid trying to solve the problem without
data.
▶ If you cannot solve the proposed problem , solve some related problem
▶ Can you use the result, or the method, for some other problem?
Classes of Problems
1. Well-defined Problems: That have specific goals, clear solutions and known
expected outcomes.
2. Ill-defined Problems: That lack clear goals, solution paths and expected solutions.
2
MODULE 1 UCEST105: Algorithmic thinking with Python
3
MODULE 1 UCEST105: Algorithmic thinking with Python
Well-Defined Problems
These problems have clear goals, a defined path to a solution, and specific criteria for
determining when the problem is solved. Let’s explore three examples:
1. Mathematical Equation:
■ Problem: Solve the equation 2x+3=7.
■ Why it’s Well-Defined: The problem has a clear goal (find the value
of x), a specific method (solve for xx using algebraic rules), and a
definite solution (x=2).
2. Crossword Puzzle:
■ Problem: Complete a standard crossword puzzle.
■ Why it’s Well-Defined: The crossword has a clear objective (fill in all
the squares with the correct words), a specific set of rules, and a single
correct solution.
3. Recipe Execution:
■ Problem: Bake a chocolate cake using a provided recipe.
■ Why it’s Well-Defined: The goal (bake a chocolate cake) is clear, the
process is outlined step-by-step in the recipe, and success is
measurable by the outcome (a baked cake that meets the description).
Ill-Defined Problems
These problems are ambiguous, lack clear criteria for solutions, and often have multiple
possible solutions. Here are three examples:
1. Designing a Sustainable City:
■ Problem: How can we design a sustainable city for the future?
■ Why it’s Ill-Defined: The problem is broad, with no single clear
solution. Various factors like environmental impact, social equity, and
economic viability come into play, and different stakeholders might
have different views on what constitutes a "sustainable" city.
2. Writing a Novel:
■ Problem: Write a compelling novel that appeals to a broad audience.
■ Why it’s Ill-Defined: The goal is subjective (what is "compelling"?),
the process can vary widely, and success is difficult to measure.
Different readers may have different interpretations of what makes the
novel appealing.
4
MODULE 1 UCEST105: Algorithmic thinking with Python
• Improves Critical Thinking – Helps analyse a situation logically and identify the
root cause of problems.
• Saves Time and Effort – Reduces trial-and-error, making solutions faster and more
efficient.
Steps :
1. Identify the problem – Start by clearly defining the issue
2. Try a solution – Attempt a possible solution
3. Evaluate the outcome – Check if the solution worked.
4. Repeat – If the solution failed, try a different one.
Example 1:
1. In terms of a broken printer for example, one could try checking the ink levels, and
if that doesn’t work, you could check to make sure the paper tray isn’t jammed. Or
maybe the printer isn’t actually connected to a laptop.
2. Restarting phone, turning off WiFi, turning off bluetooth in order to determine why
your phone is malfunctioning.
Although trial and error is not typically one of the most time-efficient strategies, it is a
commonly used one.
1. Initial Attempts: You start by trying passwords you commonly use. Eg:
”password123,” ”Qwerty2024,” etc
2. Learning from Mistakes: None of these initial attempts work. You try
variations incorporating your birthdate, pet’s name, or favorite sports team.
6
MODULE 1 UCEST105: Algorithmic thinking with Python
4. Success: Eventually, through persistent trial and error, you hit upon the
correct password: ”ToBeOrNotToBe!2024.”
2. Algorithm
1. Gather ingredients
2. Preheat Oven
3. Mix Ingredients
4. Prepare baking Pan
5. Pour Batter
6. Bake
7. Check for Doneness
8. Cool and Serve
When you run a search on the Internet, search engines like Google use algorithms to decide
which entries will appear first in your list of results. Facebook also uses algorithms to
decide which posts to display on your newsfeed.
3. Heuristics
A heuristic is another type of problem solving strategy that allow us to make decisions
quickly without having all the relevant information. It can thought of as mental shortcuts
that are used to solve problems. A “rule of thumb” is an example of a heuristic. Such a rule
saves the person time and energy when making a decision. Different types of heuristics are
used in different types of situations, but the impulse to use a heuristic occurs when one of
five conditions is met:-
● When one is faced with too much information
● When the time to make a decision is limited
● When the decision to be made is unimportant
● When there is access to very little information to use in making the decision
● When an appropriate heuristic happens to come to mind in the same moment
7
MODULE 1 UCEST105: Algorithmic thinking with Python
For example : For completing a large research project, they typically start by
● students typically brainstorm, develop a thesis or main topic,
● research the chosen topic, organize their information into an outline,
● write a rough draft
● revise and edit the rough draft, develop a final draft, organize the references
list
● proofread their work before turning in the project.
The large task becomes less overwhelming when it is broken down into a series of small
steps.
This method involves making a guess, checking if it solves the problem, and refining the
guess based on outcomes. This method is particularly useful when the problem doesn’t
have an obvious solution, and you can try different possibilities until you find the correct
one.
1. Make an Initial Guess: Start by guessing a possible solution based on what you
know.
2. Check the Guess: Determine if your guess solves the problem.
3. Refine the Guess: If the guess is incorrect, use the information you gained from
checking to make a better guess.
4. Repeat: Continue guessing, checking, and refining until you find the correct
solution.
Example : Find the number that when added to 15, gives 32.
Solution :-
● Initially make a guess as the number is 20.
● Check the guess, 15+20=35, since 35 is larger than the expected answer, refine the
guess based on the outcome.
● Now refine the guess taking the number as 18.
● Check the guess 15+18=33.
● Now the answer is very close.
● Again lower the guess to 17 and check, 15+17=32, and the guess is now correct.
8
MODULE 1 UCEST105: Algorithmic thinking with Python
c. Working backwards
This is a useful heuristic in which you begin solving the problem by focusing on the end
result.
Consider this example: Imagine you need to arrive at an important meeting by 3.00pm. To
plan your day using the working backwards heuristic, you need to start from the end result
and think about the steps needed to get there. You consider that it takes 30 minutes to get to
the meeting location, so you need to leave by 2.30pm. Before that you need an hour to
prepare,so you start getting ready at 1.30pm. If you also want to finish a task that takes an
hour before getting ready, you need to start that by 12.30pm. By working backwards, you
effectively plan your day to ensure you arrive at the meeting on time.
This strategy involves choosing and analyzing a problem at a series of smaller steps to
move closer to the goal.
The Tower of Hanoi is a mathematical puzzle. There are three rods, source(A), Auxiliary
(B) and Destination(C). Rod A contains a set of disks stacked to resemble a tower, with the
largest disk at the bottom and the smallest disk at the top. Fig:- 1 Illustrate the initial
configuration of the rods for 3 disks. The objective is to transfer the entire tower of disks in
rod A to rod C maintaining the same order of the disks.
Rules:
9
MODULE 1 UCEST105: Algorithmic thinking with Python
The solution to the puzzle calls for an application of recursive functions and recurrence
relations.
A recursive procedure for the solution of the problem for N number of disks is as follows:
1. Move the top N-1 disks from rod A to rod B using C as an auxiliary rod
2. Move the bottom disk from rod A to rod C
3. Move N-1 disks from rod B to rod C using Peg A as an auxiliary rod
The minimum number of moves required to solve a Tower of Hanoi puzzle is given by
2^N – 1, where N is the number of disks. i.e., if there are 14 disks, then minimum
number of moves needed = (2^14) - 1 = 16383.
The pictorial representation of the recursive procedure for N=4 disks is shown in Fig 2:-
10
MODULE 1 UCEST105: Algorithmic thinking with Python
11
MODULE 1 UCEST105: Algorithmic thinking with Python
Example 2: Imagine you want to plan a road trip from Trivandrum to Kashmir. Here is how
you might use means-ends analysis:
A. Define the Goal: Your ultimate goal is to drive from Trivandrum to Kashmir.
B. Analyze the Current State: You start in Trivandrum with your car ready to go.
C. Identify the Differences: The primary difference is the distance between Trivandrum
and Kashmir, which is approximately 3,700 kilometers.
D. 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, driving 500-600 kms per
day.
c. Route Planning: Choose the most efficient and scenic route, considering highways,
weather conditions, and places you want to visit.
E. Implement the Plan:
a. Day 1: Drive from Trivandrum to Bangalore, Karnataka (approx. 720 km). Refuel
in Madurai, Tamil Nadu. Overnight stay in Bangalore.
12
MODULE 1 UCEST105: Algorithmic thinking with Python
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.
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).
F. Adjust as Needed: Throughout the trip, you may need to make adjustments based on
traffic, road conditions, or personal preferences.
By breaking down the long journey into smaller 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 toward your final destination, despite the
complexity and distance of the trip.
5. Backtracking
Backtracking is a problem solving technique that involves trying different options until the
right solution is found. Backtracking algorithms are problem solving strategies that explore
various options to find the optimal solution. They operate by testing different paths, and if
a path doesn't lead to a solution they backtrack and try another route until they find the
correct one. Backtracking can also be defined as a technique that involves finding a
solution incrementally by trying different options and undoing them if they lead to a dead
end.
13
MODULE 1 UCEST105: Algorithmic thinking with Python
In the above problem, the Start node is X and destination node is G. We first move through
the route X-A-B but it reaches a dead end, then we backtrack again and select another path
X-A-C, it also encounters a dead end. Try different paths X-D-E,also reach a dead end.
Next we move through X-D-F-G and reach the destination node.
Whenever a dead end is encountered it goes back to the start node and continues searching
for a different route until the solution is discovered or all options have been considered.
Other examples :- Sudoku puzzle, Maze problem, forgetting the PIN to unlock your
smartphone etc.
14
MODULE 1 UCEST105: Algorithmic thinking with Python
The model shown in figure below assumes a single CPU (Central Processing Unit). Many
computers today have multiple CPUs, so it can be imagined the model in the figure can be
duplicated multiple times within the computer.
15
MODULE 1 UCEST105: Algorithmic thinking with Python
16
MODULE 1 UCEST105: Algorithmic thinking with Python
The I/O unit consists of the input unit and output devices. The input devices accept data
from the user, which the CPU processes. The output devices transfer the processed data
(information) to the user. The memory unit is used to store the input data, the instructions
required to process the input, and the output information.
Input devices
Input devices allow users to input data into the computer for processing. The data input to a
computer can be in the form of text, audio, video, etc. Input devices are classified into two
categories:
1. Human data entry devices – the user enters data into the computer by typing or
pointing a device to a particular location. Some examples are
b. Mouse – the most common pointing device. You move the mouse around on a
mouse pad and a small pointer called cursor follows your movements on the
computer screen.
c. Trackball – an alternative to a mouse which has a ball on the top. The cursor on
the computer screen moves in the direction in which the ball is moved.
e. Graphics tablet – converts hand-drawn images into a format suitable for computer
processing.
2. Source data entry devices –They use special equipment to collect data at the source,
create machine-readable data, and feed them directly into the computer. This category
comprises:
a. Audio input devices – It uses human voice or speech to give input. Microphones
are an example.
b. Video input devices – They accept input in the form of video or images. Video
cameras and webcams are examples.
c. Optical input devices – They use optical technology (light source) to input the
data into computers. Some common optical input devices are scanners and barcode
readers.
17
MODULE 1 UCEST105: Algorithmic thinking with Python
Output devices
An output device takes processed data from the computer and converts them into
information that can be understood by humans. The output could be on paper or can be
audio, video, etc. Output devices are classified as follows:
1. Hard copy devices – The output obtained on paper or any surface is called hard copy
output. The hard copy can be stored permanently and is portable. The hard copy output can
be read or used without a computer. Examples in this category include:
2. Soft Copy Devices – Generates a soft copy of the output on a visual display (monitor),
audio unit, or video unit. The soft copy can be stored and sent via e-mail to other users. It
also allows corrections to be made. The soft copy output requires a computer to be read or
used. This category comprises:
The Central Processing Unit (CPU) or the processor, is known as the brain of a computer. It
consists of an Arithmetic Logic Unit (ALU) and a Control Unit (CU). In addition, the CPU
also has a set of registers which are temporary storage areas for holding data and
instructions.
This unit consists of two sub-units, namely arithmetic and logic units.
18
MODULE 1 UCEST105: Algorithmic thinking with Python
II. Registers
Registers are high-speed storage areas within the CPU but have the least storage capacity.
They store data, instructions, addresses, and intermediate results of processing. Some of the
commonly used registers are:
This unit manages and coordinates the operations of all parts of the computer. The
functions of this unit are:
Memory unit
Memory is the storage space in a computer where data to be processed and instructions
required for processing are stored. The various memories can be organized hierarchically
called memory hierarchy as shown in figure below.
19
MODULE 1 UCEST105: Algorithmic thinking with Python
3. Cache memory – placed between RAM and CPU and stores the data and
instructions that are frequently used.
2. Magnetic disk – a thin plastic or metallic circular plate coated with magnetic oxide
and encased in a protective cover. Hard disk is an example.
3. Optical disk – a flat circular disk coated with reflective plastic material that can be
altered by laser light. CDs and DVDs are examples.
20
MODULE 1 UCEST105: Algorithmic thinking with Python
In solving a problem, there are some well-defined steps to be followed. It is noted that the
problem is easily solved by simply getting the input, computing something and producing
the output. We now examine the steps to problem solving within the context of various
examples.
● INPUT REQUIREMENTS
We need to understand the input we require to solve the problem. For the
given example, input requirement is two numbers whether it can be of any type, like
real number, integer number or whole number.
21
MODULE 1 UCEST105: Algorithmic thinking with Python
● OUTPUT REQUIREMENTS
Next we need to understand the output to obtain corresponding to the input
given. if we are giving real numbers as input the output obtained will be real, or if it
is integer then output will be integer.
● PROCESSING CONSIDERATIONS
We also need to understand how to reach the solution from the input given
i.e, to understand a path to reach the solution.
Formulating a model
● The next step is to understand the processing part of the problem.
● In the example given, the sum of two numbers is to be computed. A model is thus
needed for computing the sum of two numbers. If there is no such “formula”, one
must be developed.
● Assuming that the input data is two integer numbers Number1, Number2
representing a two numbers
Sum = Number1 + Number2
The main point to understand this step in the problems solving process is that it is all about
figuring out how to make use of the available data to compute an answer.
Developing an algorithm
● Next step is to develop a precise plan of what the computer is expected to do.
● An algorithm is a set of steps for solving a particular problem, or
An 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 is by using
i. Pseudo code :- an informal representation of an algorithm without
using any programming syntax
ii. Flowchart :- a diagrammatic representation of an algorithm
● Example: - Let’s use a simple math problem to develop an algorithm, a pseudo code
and a flow chart
● Algorithm
Step 1: Start
Step 2: Input the first number
Step 3: Input the second number
Step 4: Add the two numbers
Step 5: Display the result
22
MODULE 1 UCEST105: Algorithmic thinking with Python
Step 6: End
● Pseudo code
1. Start
2. Input Number1
3. Input Number2
4. Sum = Number1 + Number2
5. Output Sum
6. End
● Flow chart
23
MODULE 1 UCEST105: Algorithmic thinking with Python
● After writing the code, test it with various inputs to ensure it works as expected.
Debug and compile the program to find issues or errors that arise during testing.
● Debugging is the method of finding and fixing errors.
● Compiling is the process of converting a program into instructions that can be
understood by the computer.
Testing the Program
● Once a program has been written and compiled, the next critical step is to ensure
that whether the program performs the intended task correctly. Testing the program
involves running it with various inputs to verify its accuracy and reliability.
● Running a program is the process of telling the computer to evaluate the compiled
instructions.
● If the program runs correctly, the expected output should be displayed.
● If the program doesn’t run correctly for some inputs then the user has to go back to
the algorithm development step that handles all situations that could arise.
o If the output is incorrect, it could be due to the algorithm not being properly
implemented in the program. or
o A flaw or a bug in the algorithm itself, which does not account for certain
situations.
Bugs are errors in a program that cause it to produce incorrect or undesirable
results.
Evaluating the Solution
● Once a program produces a result, revisit the original problem.
● Ensure the output is formatted as a proper solution.
● Examine if the result aligns with the original intent.
● Determine if the output meets the problem's requirements.
● Remember that the computer executes instructions as given. The user must
interpret results to determine effectiveness.
INPUT REQUIREMENT: get all the grades … possibly by typing them in via the
keyboard
● Key Questions:
o What input data/information is available?
o What does the data represent, and in what format?
o Is anything missing from the data?
o Do I have everything needed to solve the problem?
24 .
MODULE 1 UCEST105: Algorithmic thinking with Python
In the example given, the average of the incoming grades is to be computed. A model (or
formula) is thus needed for computing the average of a bunch of numbers. If there is no
such “formula”, one must be developed.
· Assuming that the input data is a bunch of integers or real numbers 𝑥1, 𝑥2, ⋯ , 𝑥𝑛
representing a grade percentage, the following computational model may apply:
𝐴𝑣𝑒𝑟𝑎𝑔𝑒1 = (𝑥1 + 𝑥2 + 𝑥3 + ⋯ + 𝑥𝑛 )/𝑛 where the output will be a number from 0 to 100.
·
The challenge facing in the above calculation is Letter grades (e.g., A, B-, C+)
cannot be directly added or divided.Solution is Assign Values to letter grades
o Convert letter grades to numerical equivalents
𝐴 + = 12 𝐴 = 11 𝐴 − = 10 𝐵+=9
𝐵=8 𝐵−=7 𝐶+=6 𝐶=5
𝐶−=4 𝐷+=3 𝐷=2 𝐷−=1 𝐹=0
o If it is assumed that these newly assigned grade numbers are 𝑦1, 𝑦2, ⋯, 𝑦𝑛, then
the following computational model may be used:
25
MODULE 1 UCEST105: Algorithmic thinking with Python
The main point to understand this step in the problems solving process is that it is all about
figuring out how to make use of the available data to compute an answer.
Developing an algorithm:
Algorithm
STEP 1: Start
STEP 2: Read number of students, n
STEP 2: Read the marks of n students
STEP 3: Compute average using the formula
STEP 4: Display Average
STEP 5: Stop
Pseudo code
1. Start
2. Input n
3. Input the marks of n students, x1,x2,x3,…,xn
4. Average=(x1+x2+x3+…+xn)/n
5. Output Average
6. End
Flow chart
26
MODULE 1 UCEST105: Algorithmic thinking with Python
· # Program in Python
n = int("input(Enter number"))
sum = 0
# loop from 1 to n
for num in range(1,n+1,1):
sum = sum+num
average=sum/n
print("Average of ",n,"numbers is: ",average)
Test the program: You create a test suite with various types of numbers and check whether
the output obtained is correct or not.
27
MODULE 1 UCEST105: Algorithmic thinking with Python
INTRODUCTION
PROGRAMMING LANGUAGES
Programming languages are used to write programs that useare precise
representations of algorithms and control the behavior of a computer. Each language has a
unique set of keywords (words that it understands) and syntax (set of rules) to organize the
program instructions.
Programming languages fall into three categories:
1. Machine language:- is what the computer can understand, but it is difficult for the
programmer to understand. Machine languages consist of binary numbers only. No
translation of the program is needed and it can be executed very fast. It is
machine-dependent ie. A machine-level program written for one type of computer may not
work on another type.
28
MODULE 1 UCEST105: Algorithmic thinking with Python
3. High-level language:- is easier to understand and use for the programmer but difficult
for the computer. The programs written in high-level languages contain English-like
statements as well as programming.
Eg:- C, FORTRAN, Pascal, Java, Python etc. that enables a programmer to write programs.
High level language programs are easier to write, read, and understand. They are easily
portable from one computer to another, since they are not machine-dependent.Two types-
static and dynamic
Example : To add 3 and 6, the high level language code will be 3+6.
Here ‘+’ is the operator for addition.
29
MODULE 1 UCEST105: Algorithmic thinking with Python
TRANSLATOR SOFTWARE
The computer can understand only machine code (strings of 0’s and 1’s). Thus when the
program is written in other languages (assembly or high-level languages) has to be
converted to machine code. This conversion is called translation and is performed by the
translator software.
The original program is called source code, and the translated code (object code) is the
target code.
There are three types of translator software as discussed below:
1. Assembler : is a software that converts a program written in assembly language into
machine code.
2. Compiler : is a software that translates programs written in high-level language to
machine code.
3. Interpreter : The interpreter also converts the high-level language program into
machine code. However, the reads the source code line-by-line, converts it into
machine code, executes the line, and then proceeds to the next line.
30
MODULE 1 UCEST105: Algorithmic thinking with Python
INTRODUCTION TO PYTHON
Python is a general purpose, high-level, interpreted programming language developed by
Guido van Rossum in the late 1980s at the National Research Institute for Mathematics
and Computer Science in the Netherlands. Python is one of the most popular and widely
used programming languages used for a set of tasks including Console based, GUI based,
web programming and data analysis. Python is named after the comedy television show
Monty Python's Flying Circus.
FEATURES OF PYTHON
31
MODULE 1 UCEST105: Algorithmic thinking with Python
APPLICATIONS OF PYTHON
32
MODULE 1 UCEST105: Algorithmic thinking with Python
The Python shell is an interactive terminal-based environment wherein you can directly
communicate with the Python interpreter. First, you open a terminal and type python3.
Now the shell turns up with a welcome message as shown below.
user@Ubuntu2204LTS:~$ python3
Python 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information
The symbol >>> is called the shell prompt. This symbol prompts you for Python
statements. When you enter a statement in the shell, the Python interpreter processes it and
displays the result, if any, then followed by a new prompt as shown below:
>>> "Welcome to the world of Python programming"
'Welcome to the world of Python programming'
>>>
Using Script File
Interpreter prompt is good to run the individual statements of the code. However if we
want to execute multiple python statements at a time instead of executing one by one, then
we can use script files. We need to write our script into a file which can be executed later.
For this purpose, open an editor like notepad, create a file named filename.py (python used
.py extension) and write the python script in it.
Running as a script
1. Combine all the statements that you wish to execute into a Python program.
Program is known as a script and should be saved with the “py” extension, for
example sample.py.
2. You may use some text editor to create your script. gedit, vim are some of the
editors that you can probably use.
3. Then open a terminal in the directory where the script is stored. To run your script
(assuming the name is First.py), just give
python3 First.py
Now the script will be executed and you get the desired output.
33
MODULE 1 UCEST105: Algorithmic thinking with Python
Example : Suppose you have written a script sample.py to display the message “My first
Python program!”. This is how you run it (The second line below shows the output):
user@Ubuntu2204LTS:~$ python3 First.py
My first Python program!
Comments in Python
● Comments are used in a programming language to describe the program or to hide
some part of code from the interpreter.
● Comment is not a part of the program, but it enhances the interactivity of the
program and makes the program readable.
● Python supports two types of comments:
1. Single Line Comment
2. Multi Line Comment
Character set
● Alphabets: All capital (A-Z) and small (a-z) alphabets.
● Digits: All digits 0-9.
● Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $
%^`&*()_+–={}[]\
● White Spaces: White spaces like tab space, blank space, newline, and carriage return.
34
MODULE 1 UCEST105: Algorithmic thinking with Python
Python tokens
● A token is the smallest individual unit in a python program.
● All statements and instructions in a program are built with tokens.
● The various tokens in python are :
2. Identifiers
● Identifiers are the names given to any variable, function, class, list, methods, etc. for
their identification.
● Python has some rules and regulations to name an identifier.
● Rules to name an identifier:-
■ Python is case-sensitive. So case matters in naming identifiers. And hence
geeks and Geeks are two different identifiers.
■ Identifiers start with a capital letter (A-Z) , a small letter (az) or an
35
MODULE 1 UCEST105: Algorithmic thinking with Python
underscore( _ ).
■ It can’t start with any other character.
■ Except for letters and underscore, digits can also be a part of an identifier but
can’t be the first character of it.
■ Any other special characters or whitespaces are strictly prohibited in an
identifier.
■ An identifier can’t be a keyword.
EXAMPLE
36
MODULE 1 UCEST105: Algorithmic thinking with Python
EXAMPLE
3. Literals (Constants)
● Python literals are a data type and can hold any value type, such as strings, numbers,
and more
● The way of using literals depends on its type.
● The various types of literals used in the Python program are as follows:
■ String literals
■ Numeric literals - integer, float, complex
■ Boolean literals
■ Literal Collections - list, tuple, set, dictionary
Numeric and String data types in Python
4. Data Types
● Data Types specifies what type of data will be stored in variables.
● Variables can hold values of different data types.
● Python is dynamically typed, hence we need not define the type of the variable
while declaring it.
37
MODULE 1 UCEST105: Algorithmic thinking with Python
A. Numeric datatype
● The numeric data type in Python represents the data that has a numeric value.
● A numeric value can be an integer, a floating number, or even a complex
number.
● There are three numeric types in Python:
1. int
2. float
3. complex
38
MODULE 1 UCEST105: Algorithmic thinking with Python
EXAMPLE
PROGRAM
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1 + 2j
print(num3, 'is of type', type(num3))
OUTPUT
x=5 # int
y = 2.5 # float
z = x + y # x is implicitly converted to float
print(z) # Output: 7.5
print(type(z)) # <class 'float'>
x = "10" # str
y = int(x) # explicitly convert string to integer
print(y + 5) # Output: 15
print(type(y)) # <class 'int'>
Escape sequence
The escape sequence is a sequence of characters treated as special when the Python
interpreter encounters it in the string literal. The escape sequence is represented using the
backslash (‘\’) followed by the character.
\r:Moves the cursor to the beginning of the current line without advancing to the next line.
\b:Moves the cursor one position backward, effectively deleting the previous character.
\f:Advances the cursor to the next page. In modern consoles, it often acts like a new line or
is ignored.
EXAMPLE
40
MODULE 1 UCEST105: Algorithmic thinking with Python
■ String
■ List
■ Tuple
a. String:- A string is a collection of one or more characters. Strings are represented by
either single, double or triple quotes.
EXAMPLE
b. List
List is an ordered sequence of some data written using square brackets([]) and commas(,).
List is mutable (means values in the list can be changed during execution time).
EXAMPLE
41
MODULE 1 UCEST105: Algorithmic thinking with Python
c. Tuple
The tuple is another data type which is a sequence of data similar to a list. But it is
immutable. That means data in a tuple is write-protected. Data in a tuple is written using
parentheses and commas.
EXAMPLE
C. Dictionary
Dictionary is an ordered sequence of data of key-value pair form. Dictionaries are written
within curly braces in the form key:value.
PROGRAM
OUTPUT
<class 'dict'>
D. Set
Set is an unordered collection of unique items defined by values separated by commas
inside braces{}.
42
MODULE 1 UCEST105: Algorithmic thinking with Python
E. Boolean
Boolean data type that has one of two possible values (usually denoted True and False)
which is intended to represent the two truth values of Boolean algebra.
EXAMPLE
import math
● Various functions in math module are:-
NUMERIC FUNCTIONS
1. math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
43
College
MODULE 1 UCEST105: Algorithmic thinking with Python
2. math.ceil()
The ceil() function approximates the given number to the smallest integer,
greater than or equal to the given floating point number.
>>>math.ceil(4.5867)
5
3. math.floor()
The floor() function returns the largest integer less than or equal to the given
number.
>>>math.floor(4.5687)
4
4. math.fabs()
5. math.pi()
6. math.factorial()
7. math.gcd()
44
College
MODULE 1 UCEST105: Algorithmic thinking with Python
9. math.pow()
The math.pow() method receives two float arguments, raises the first to the
second and returns the result. In other words, pow(2,3) is equivalent to 2**3.
>>>math.pow(2,4)
16.0
10. math.log()
Used to calculate the logarithmic value of a with base b
>>>print ("The value of log 2 with base 3 is : ")
>>>print (math.log(2,3))
The value of log 2 with base 3 is : 0.6309297535714574
OUTPUT
45
College
MODULE 1 UCEST105: Algorithmic thinking with Python
Using the Python Standard Library for handling basic I/O - input(),
print()
Python offers us several built-in functions that make it easy to create a program quickly.
Two of the most commonly used built-in functions are the input() and print() functions
that are used for frequent input and output operations, respectively.
Python Input
To run an application, programmers often need to obtain input in Python from a user. The
simplest way to do this is to use the input() function. The function pauses program execution to
let the user type a line of information from the keyboard. When the user hits “Enter”, the input is
read and returned as a string.
Syntax:-
input([<prompt>])
where the prompt is an optional string that we wish to display for the user.
EXAMPLE
By default, the input() function accepts only string arguments. However, we can convert
this to a number by using the int() of float() functions.
EXAMPLE
46
MODULE 1 UCEST105: Algorithmic thinking with Python
Or
For taking multiple inputs from the user in a single line we use the function split().
EXAMPLE
Python Output
Once a program accepts input in Python and processes the data, it needs to present the data
back to the user as output. You can choose to display the data output to the console directly
or show it on a screen.
We use the print() function to display the output data to the (screen).
Syntax:-
print(<obj>,...,<obj>)
Using the above syntax, we can pass several objects (<obj>) in the print() function by
separating them with a comma.
EXAMPLE
>>>print(100)
100
>>>num = 65
>>>print ('The value of the number is', num)
47
MODULE 1 UCEST105: Algorithmic thinking with Python
Another Syntax:-
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
EXAMPLE
OUTPUT
Value of a: 0002
Simple answer can be given using the expression 4 + 5 is equal to 9. Here, 4 and 5 are
called operands and + is called operator.
1. Arithmetic Operators
2. Comparison (Relational) Operators
48
MODULE 1 UCEST105: Algorithmic thinking with Python
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
49
MODULE 1 UCEST105: Algorithmic thinking with Python
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)
This code defines the two variables "a" and "b." It then applies several arithmetic
operations to them (including addition, subtraction, multiplication, division, modulus,
exponentiation, and floor division) and outputs the results.
Output
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b:1
a ** b : 16679880978201
a // b : 2
50
MODULE 1 UCEST105: Algorithmic thinking with Python
This code compares the values of python variables 'a' and 'b' and prints if they are equal,
not equal, greater than, less than, more than or equal to, and less than or equal to each
other.
Output
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
51
MODULE 1 UCEST105: Algorithmic thinking with Python
= Assignment Operator a = 10
47
MODULE 1 UCEST105: Algorithmic thinking with Python
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)
The Python assignment operators are shown in this code in the Python Editor. It begins
with the value of 'a' equal to 10, and then goes through the steps of addition, subtraction,
multiplication, division, remainder, exponentiation, and floor division, updating 'a' as
necessary and outputting the results.
Output
a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
48
MODULE 1 UCEST105: Algorithmic thinking with Python
<< Binary Left Shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
Output
a & b : 12
a | b : 61
a ^ b : 49
~a : -61
49
MODULE 1 UCEST105: Algorithmic thinking with Python
a >> 2 : 240
a >> 2 : 15
● Python logical operators are used to compose Boolean expressions and evaluate
their truth values.
● They are required for the creation of conditional statements as well as for managing
the flow of execution in programs.
● Python has three basic logical operators: AND, OR, and NOT.
and Logical If both of the operands are true then the condition (a and b) is true.
AND becomes true.
not Logical Used to reverse the logical state of its operand Not(a and b) is
NOT false.
The code assigns the values 5 and 10 to variables x and y. It determines whether x is larger
than 3 and y is less than 15. If both conditions are met, it writes "Both x and y are within
the specified range."
Output
Both x and y are within the specified range
● Python membership operators are used to determine whether or not a certain value
occurs within a sequence.
● They make it simple to determine the membership of elements in various Python
data structures such as lists, tuples, sets, and strings.
50
MODULE 1 UCEST105: Algorithmic thinking with Python
● Python has two primary membership operators: the in and not in operators.
not in Evaluates to true if it does not find a x not in y, here not in results in
variable in the specified sequence and a 1 if x is not a member of
false otherwise. sequence y.
The code defines a list of fruits and tests to see if the word "banana" appears in the list. If it
is present, “True” is printed on screen.
Output
True
● Python identity operators are used to compare two objects' memory addresses rather
than their values.
● If the two objects refer to the same memory address, they evaluate to True;
otherwise, they evaluate to False.
● Python includes two identity operators: the is and is not operators.
51
MODULE 1 UCEST105: Algorithmic thinking with Python
y=5
print(x is y)
The code sets the variables x and y to 10 and 5, respectively. Then check whether the both
values are equal using is operator. If correct, True value will be displayed else false value.
Output
False
OPERATOR PRECEDENCE
When an expression or statement involves multiple operators then it will be resolve using
the following operator precedence chart :
denote the order in which the various operators are applied. The final result is
1, which is assigned to R.
52
MODULE 1 UCEST105: Algorithmic thinking with Python
53
MODULE 1 UCEST105: Algorithmic thinking with Python
Part A (3 MARKS)
1. You are asked to solve a jigsaw puzzle without a reference picture. How will you solve it using
trial and error method?
A.
Trial and Error Method: It is a problem-solving technique where different possibilities are tried,
and errors are eliminated until the correct solution is found.
Steps to solve jigsaw puzzle:
1. Sort the pieces (edges, corners, colors).
2. Assemble the frame using edge and corner pieces.
3. Work on sections by grouping similar colors/patterns.
4. Test and fit pieces through trial and error.
5. Combine clusters and fill remaining gaps.
2. Given the input "12345", write a Python code snippet to check if it is numeric
A.
3. Identify the most suitable problem-solving strategies for the following use cases. Justify your
answer:
i) You are solving a complex Sudoku puzzle and are unsure how to proceed as you approach the
final few cells.
ii) You are tasked with planning a family trip that involves selecting a destination, booking flights,
and finding accommodation within a budget.
A.
i) Sudoku Puzzle: BacktrackingStrategy: Use backtracking.Justification: Backtracking is
effective for problems involving constraints like Sudoku. You can systematically try placing
numbers in cells and backtrack if you encounter conflicts, ensuring that all possibilities are explored
efficiently
ii) Planning a Family Trip: Means-Ends AnalysisStrategy: Use means-ends
analysis.Justification: This strategy involves breaking down the goal (planning the trip) into
smaller tasks (destination, flights, accommodation) and solving each subproblem while considering
constraints like the budget, making it an efficient approach for multi-step problems
4. What will be the result of the following expressions in Python?
i) (50 - 5 * 6) // 4
54
MODULE 1 UCEST105: Algorithmic thinking with Python
A.
(i)Expression:
(50−5∗6)//4
1. Inside parentheses:
5∗6=30
2. Subtraction:
50−30=20
3. Floor division by 4:
20//4=5
Answer is 5
(ii)
Check (10 < 5) → False
not (False) → True
Check (5 == 5) → True
Now expression is: True or True → True
(iii) In and, if the first value is truthy, Python returns the second value.
Here, True is truthy → so it returns 5
55
MODULE 1 UCEST105: Algorithmic thinking with Python
b) Your college is located in a metropolitan city and you are new to that city. You would like to go
out for dinner with your friends. Explain how heuristics approach can be used to find the best
restaurant for dinner
A) Heuristics are simple rules or shortcuts used to make quick and efficient decisions instead of
checking all possibilities
1. Define the Key Criteria
• What it means: Decide what factors or standards are most important for making the decision.
• Example: If you’re choosing a restaurant, key criteria could be price, location, cuisine type, and
customer reviews.
• Why it matters: This gives you a clear focus on what really matters, so you don’t get distracted by
irrelevant details.
56
MODULE 1 UCEST105: Algorithmic thinking with Python
• What it means: Choose the option that best fits your criteria after considering the data and applying
heuristics.
• Example: You decide on the restaurant that is highly rated, within your budget, and serves the
cuisine you want.
• Why it matters: This is the outcome of your structured decision-making process.
2. a) You are asked to develop new campus management software for your college. How will you apply
Means-Ends Analysis to develop the software? (5 marks)
b) Given the area of a circle. Write a Python program to calculate the radius of the circle using the math
module.
a)
57
MODULE 1 UCEST105: Algorithmic thinking with Python
3. a) Walk through the six problem-solving steps to calculate the area of a circle.(6marks)
A)
Step: Read the problem carefully. Identify what is given and what needs to be found.
Example: The problem asks for the area of a circle, given the radius.
Formula: Area = π × r²
4. Break into Sub-Problems
58
MODULE 1 UCEST105: Algorithmic thinking with Python
Multiply by π.
Step: Carry out the calculations step by step using a program or manual computation.
import math
r = float(input("Enter radius of the circle: "))
area = math.pi * r**2
print(f"Area of the circle is: {area}")
b) What are the basic data types in Python? Provide examples for each
A)
1. Integer (int)
• Whole numbers, positive or negative, without decimals.
Example:
age = 25
year = -2025
2. Float (float)
Numbers with decimal points.
Example:
price = 99.99
temperature = -4.5
3. String (str)
Sequence of characters enclosed in single (' ') or double (" ") quotes.
• Example:
name = "Alice"
greeting = 'Hello, World!'
59
MODULE 1 UCEST105: Algorithmic thinking with Python
2. Heuristics
• Definition: A problem-solving approach using rules of thumb, shortcuts, or
educated guesses.
• Characteristics:
o Does not guarantee a perfect solution.
o Provides a quicker solution.
o Useful for complex or poorly defined problems.
• Example: Choosing the shortest route on a map using “take roads that look
shortest” rather than calculating every possible path.
b) Write a Python program to convert the time input in minutes to hours and minutes.
For example, 85 minutes is 1 hour 25 minutes
A)
minutes = int(input("Enter time in minutes: "))
hours = minutes // 60
remaining_minutes = minutes % 60
print(f"{hours} hour(s) and {remaining_minutes} minute(s)")
60