0% found this document useful (0 votes)
19 views32 pages

ATP Module 1

Uploaded by

aadhikassim
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)
19 views32 pages

ATP Module 1

Uploaded by

aadhikassim
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/ 32

MODULE - 01

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.

PROBLEM

A problem is a situation or issue that presents a challenge or difficulty that needs to be resolved. It
often involves a gap between the current state and a desired state, requiring analysis, decision-making,
and action to find a solution. Problems can be simple or complex, ranging from everyday dilemmas to
significant societal issues.

A problem is defined by four conditions or parameters. They are:-

● Goal
● Set of resources
● Commitment.

If one or more of these components are missing, the problem is not well defined.Problems can be
categorized into two: -

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.

Differentiate between Well-defined problems and Ill-defined problems.

Well-defined Problems Ill-defined Problems


Clear goals and Objectives Unclear and Vague goals and Objectives
Specific, measurable outcomes Multiple , conflicting outcomes
Well defined constraints Ambiguous or uncertain constraints
Relevant data available Insufficient data available
Single , Identifiable Solution Multiple possible solutions
Logical, step by step approach Requires creative, iterative approach
Ex : Chess Game Ex: Paint a beautiful picture
UCEST105- AlGORITHMIC THINKING WITH PYTHON 1 Prepared By Mrs. Bini Charles, TIST
Write any three Well-defined and Ill-defined problems, Justify your answer.

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 mighthave different views on what constitutes a
"sustainable" city.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 2 Prepared By Mrs. Bini Charles, TIST
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 thenovel appealing.
3. Resolving Workplace Conflict:

■ Problem: Resolve a conflict between two team members in the workplace.


■ Why it’s Ill-Defined: The problem is complex with no clear solution. It involves
interpersonal dynamics, emotions, and communication styles, and what works in
one situation might not work in another. Multiple solutions may exist, and the
"right" one depends on various factors.
Summary

• Well-Defined Problems are structured, with a clear path and solution.


• Ill-Defined Problems are open-ended, ambiguous, and often subjective. Understanding the
nature of the problem helps in choosing the right approach to solving it.

PROBLEM SOLVING

Problem-solving is the process of finding solutions to challenges. These challenges can be simple or
complex, requiring us to identify the issue, brainstorm solutions, and apply the best strategy.

STEPS TO EFFECTIVE PROBLEM SOLVING

1. Define the Problem: Clearly articulate what the issue is. Identify the root cause and the impact it has. This
step often involves gathering information and understanding the context.
2. Brainstorm Possible Solutions: Generate a variety of ideas without judgment. Encourage creative thinking
and consider all potential solutions, no matter how unconventional.
3. Evaluate the Solutions: Assess the feasibility, pros, and cons of each option. Consider factors like resources,
time, and potential outcomes to determine the most viable solutions.
4. Implement the Solution: Put the chosen solution into action. Develop a plan, assign responsibilities, and
communicate effectively with all stakeholders involved.
5. Monitor & Adjust: After implementation, track the results to see if the problem is resolved. Be prepared to
make adjustments as necessary based on feedback and outcomes.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 3 Prepared By Mrs. Bini Charles, TIST
PROBLEM SOLVING STRATEGIES

Problem-solving strategies are plans of action to find solutions. There are various strategies, each with
its own method and application.

1. Trial and Error: This involves trying multiple solutions until the problem is resolved.
2. Heuristics :These are mental shortcuts that simplify decision-making and problem-solving.
3. Means-Ends Analysis ;This strategy involves breaking down a problem into smaller, more
manageable sub-problems.
4. Backtracking : This strategy involves starting with the desired outcome and working backward to
the current state

1. 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 ”MyDog-Tommy.”
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.”
UCEST105- AlGORITHMIC THINKING WITH PYTHON 4 Prepared By Mrs. Bini Charles, TIST
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.

2. 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. 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.
3. 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.
o Define the Goal: Your ultimate goal is to drive from Trivandrum to Kashmir.
o Analyze the Current State: You start in Trivandrum with your car ready to go.
UCEST105- AlGORITHMIC THINKING WITH PYTHON 5 Prepared By Mrs. Bini Charles, TIST
o Identify the Differences: The primary difference is the distance between Trivandrum and
Kashmir, which is approximately 3,700 kilometers.
o Set Sub-Goals (Means):
• Fuel and Rest Stops: Determine where you will need to stop for fuel and rest.
• Daily Driving Targets: Break the trip into daily segments, such as driving 500-600
kilometers per day.
• Route Planning: Choose the most efficient and scenic route, considering highways,
weather conditions, and places you want to visit.
o Implement the Plan:
§ Day 1: Drive from Trivandrum to Bangalore, Karnataka (approx.720 km). Refuel in Madurai,
Tamil Nadu. Overnight stay in Bangalore.
§ Day 2: Drive from Bangalore to Hyderabad, Telangana (approx.570 km). Refuel in Anantapur,
Andhra Pradesh. Overnight stay inHyderabad.
§ Day 3: Drive from Hyderabad to Nagpur, Maharashtra (approx. 500km). Refuel in Adilabad,
Telangana. Overnight stay in Nagpur.
§ Day 4: Drive from Nagpur to Jhansi, Uttar Pradesh (approx. 580km). Refuel in Sagar, Madhya
Pradesh. Overnight stay in Jhansi.
§ 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.
§ Day 6: Drive from Agra to Chandigarh (approx. 450 km). Refuel in Karnal, Haryana. Overnight
stay in Chandigarh.
§ Day 7: Drive from Chandigarh to Jammu (approx. 350 km). Refuel in Pathankot, Punjab.
Overnight stay in Jammu.
§ Day 8: Drive from Jammu to Srinagar, Kashmir (approx. 270 km).
o 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, achievable segments and ad-dressing
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.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 6 Prepared By Mrs. Bini Charles, TIST
Importance of Understanding Multiple Problem-Solving Strategies
ü Adaptability: Different problems require different approaches. Under-standing multiple strategies
allows for flexibility and adaptability in problem-solving.
ü 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.

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.
Other Problem-solving Strategies
Here are some examples of problem-solving strategies that may equally be adopted to see which works
best for you in different situations:
i. Brainstorming
Brainstorming involves generating a wide range of ideas and solutions to a problem without
immediately judging or analyzing them. The goal is to encourage creative thinking and explore various
possibilities. In a team meeting to improve customer satisfaction, everyone contributes different ideas,
UCEST105- AlGORITHMIC THINKING WITH PYTHON 7 Prepared By Mrs. Bini Charles, TIST
such as enhancing product quality, improving customer service training, offering loyalty programs, and
using customer feedback to make improvements. These ideas are later evaluated and the best ones are
implemented.

ii. Lateral Thinking


Lateral thinking is about looking at problems from new and unconventional angles. It involves thinking
outside the box and challenging established patterns and assumptions.A company facing declining sales
of a product might use lateral thinking to identify new uses for the product or new markets to target,
rather than just trying to improve the existing product or marketing strategy.

iii.Root Cause Analysis


Root cause analysis involves identifying the fundamental cause of a problem rather than just addressing
its symptoms. The goal is to prevent the problem from recurring by solving its underlying issues. If a
factory’s production line frequently breaks down, rather than just repairing the machinery each time,
the team conducts a root cause analysis and discovers that poor maintenance scheduling is the
underlying issue. By implementing a better maintenance plan, they reduce the breakdowns.

iv. Mind Mapping


Mind mapping is a visual tool for organizing information. It helps in brainstorming, understanding, and
solving problems by visually connecting ideas and concepts. When planning a large event, an organizer
creates a mind map with the event at the center, branching out into categories like venue, catering,
entertainment, invitations, and logistics. Each category further branches into specific tasks and
considerations.

v. SWOT Analysis
SWOT analysis involves evaluating the Strengths, Weaknesses, Opportunities, and Threats related to a
particular problem or decision. It helps in understanding both internal and external factors that impact
the situation.
A business firm considering a new product launch performs a SWOT analysis. They identify their
strengths (strong brand, good distribution network), weaknesses (limited R&D budget), opportunities
(market demand, potential partnerships), and threats (competition, economic downturn).
This analysis guides their decision-making process.
UCEST105- AlGORITHMIC THINKING WITH PYTHON 8 Prepared By Mrs. Bini Charles, TIST
vi. Decision Matrix
A decision matrix, also known as a decision grid or Pugh matrix, helps in evaluating and prioritizing a
list of options. It involves listing options and criteria, assigning weights to each criterion, and scoring
each option based on the criteria. A family deciding on a new car creates a decision matrix with criteria
such as cost, fuel efficiency, safety features, and brand reputation. They rate each car option against
these criteria and calculate a total score to make an informed choice.

vii. Simulation
Simulation involves creating a model of a real-world system and experimenting with it to understand
how the system behaves under different conditions. It helps in predicting outcomes and identifying the
best course of action. Urban planners use traffic simulation software to model the impact of new road
constructions on traffic flow. By testing different scenarios, they can design the most effective road
network to reduce congestion.
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.
Computer as a model of computation

UCEST105- AlGORITHMIC THINKING WITH PYTHON 9 Prepared By Mrs. Bini Charles, TIST
A computer is an electronic device that processes data according to programmed instructions. It
performs essential functions such as input (receiving data), processing (calculating and manipulating
data), storage (saving information temporarily or permanently), and output (producing results).
Ranging from simple calculators to powerful servers, computers are vital tools in various fields,
enabling tasks like data analysis, communication, and automation.
1. Input/Output (I/O)
• Input: Devices that allow users to enter data into the computer. Examples include:
o Keyboard: For typing text and commands.
o Mouse: For navigating and selecting items on the screen.
o Scanner: For digitizing physical documents.
• Output: Devices that present processed data to users. Examples include:
o Monitor: Displays visual output, such as images and text.
o Printer: Produces physical copies of documents.
o Speakers: Output audio signals.
2. CPU (Central Processing Unit)
• The CPU is the brain of the computer, responsible for executing instructions and processing
data. It consists of:
• ALU (Arithmetic Logic Unit): Performs arithmetic operations (like addition and
subtraction) and logical operations (like comparisons). For example, the ALU can calculate
the sum of two numbers or determine if one number is greater than another.
• CU (Control Unit): Directs the operation of the CPU and coordinates how data moves
between the CPU, memory, and I/O devices. For example, it fetches instructions from
memory, decodes them, and executes them.
• Registers: Small, fast storage locations within the CPU that temporarily hold data and
instructions. For example, a register might hold the result of a calculation before it's sent to
main memory.
3. Main Memory (RAM)
• Random Access Memory (RAM): A type of volatile memory that temporarily stores data
and instructions currently being used by the CPU. For example, when you open a program,
it is loaded into RAM for quick access. If the computer is turned off, the data in RAM is
lost.
4. Secondary Memory
UCEST105- AlGORITHMIC THINKING WITH PYTHON 10 Prepared By Mrs. Bini Charles, TIST
• Secondary Memory: Non-volatile storage that retains data even when the computer is
powered off. It is used for long-term storage of data and programs. Examples include:
o Hard Disk Drive (HDD): A traditional spinning disk used for storing large amounts
of data.
o Solid State Drive (SSD): A faster, more reliable storage option that uses flash
memory.
o USB Flash Drive: A portable storage device that allows easy data transfer between
computers.
The Problem solving process
Let us now explore how computers can be put to solving problems:
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 mostcommonly 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.
UCEST105- AlGORITHMIC THINKING WITH PYTHON 11 Prepared By Mrs. Bini Charles, TIST
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.

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.

A case study - The Discriminant calculator

Real problem at hand – 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

UCEST105- AlGORITHMIC THINKING WITH PYTHON 12 Prepared By Mrs. Bini Charles, TIST
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 = b2 − 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

You will learn more about pseudocodes in Chapter 2.

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 the below Table. Each row
denotes a set of inputs (a, b, and c) and the expected output (d) with which the actual output is to be
compared.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 13 Prepared By Mrs. Bini Charles, TIST
ESSENTIALS OF PYTHON PROGRAMMING

Python

• High-Level Language: Python abstracts complex details, making it easier to write and read code.
• Interpreted: Code is executed line-by-line, which facilitates debugging and testing.
• Clear Syntax: Emphasizes readability and simplicity, reducing the learning curve for beginners.
• Multi-Paradigm: Supports procedural, object-oriented, and functional programming styles.
• Extensive Standard Library: Comes with a rich set of built-in modules and functions for various
tasks.
• Vibrant Ecosystem: Boasts a vast array of third-party packages and libraries for diverse
applications.
• Popular Applications: Widely used in web development, data analysis, artificial intelligence,
scientific computing, and automation.

FEATURES OF PYTHON

UCEST105- AlGORITHMIC THINKING WITH PYTHON 14 Prepared By Mrs. Bini Charles, TIST
Python Interpreter

Fig :Steps in interpreting a Python


program

i. The interpreter performs a sequence of steps to execute your script:


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.
ii. If the expression is well formed, the interpreter then translates it to an executable form called byte code. The
Syntax checker and Translator component of the interpreter is responsible for verifying the syntax of the
statements and translating valid statements to byte code.
iii. Then, the byte code is sent to another interpreter component called the Python Virtual Machine (PVM) for
execution. If any error occurs during execution, the process is halted with a runtime error message. Otherwise,
the execution runs to completion and the output is produced.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 15 Prepared By Mrs. Bini Charles, TIST
Steps in learning Python

1. Character set
ü 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:
a. upper case alphabets (A–Z)
b. lower case alphabets (a–z)
c. digits (0–9)
d. special symbols like @,#,%,$ etc.

Python maps each valid character to an integer value called ASCII value. (ASCII is the abbreviation of
American Standard Code for Information Inter- change.) For example, the ASCII value of character 'A'
is 65.

2. Constants, variables, and keywords

Constants

A ‘constant’ is an entity whose value doesn’t change.

Definition: A constant is a value that does not change during the execution of a program.

Example: PI = 3.14

Variables

§ The data on which programs operate are stored in various memory locations. To simplify the
retrieval and use of data values, these memory locations are given names. Since the value
stored in each location may change occasionally, the names given to these locations are
called ‘variable names’ or simply ‘variables’.
§ Thus, a variable is a name that refers to a value.
§ ‘_’ is a valid variable name.
§ The names can include both letters and digits; however, there are restrictions:

UCEST105- AlGORITHMIC THINKING WITH PYTHON 16 Prepared By Mrs. Bini Charles, TIST
1) Variable names must start with a letter or the underscore ‘_’ and can be followed
by any number of letters, digits, or underscores.
2) Variable names are case sensitive; thus, the variable COUNT is a different name
from the variable count.
3) Variable names cannot be a keyword. Keywords(also called reserved words) are
special words, reserved for other purposes; thus, they cannot be used as variable
names. Python has thirty-three keywords. All the keywords except True, False, and
None are in lowercase, and they must be written as is.

Fig: Key words (Reserved words in 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 :

UCEST105- AlGORITHMIC THINKING WITH PYTHON 17 Prepared By Mrs. Bini Charles, TIST
Data types

• Any data item stored in memory has an associated data type. For example, your roll
number is stored as a number whereas, your name is stored as a string.
• The data type of an item defines the operations that can be performed on it, and how the
values are stored in memory. Python supports the following data types:

o Number
o String
o List
o Tuple
o Set
o Dictionary

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

int

• The integers include numbers that do not have decimal point. The int data type supports
integers ranging from −231 to 231 − 1.

float

• Python uses float type to represent real numbers (with decimal points). The values of float
type range approximately from −10308 to 10308 and have 16 digits of precision (number of
digits after the decimal point).
• Example: 3.45, 8.9, 8.9876….etc

Strings

• A string literal or a string is a sequence of characters enclosed in a pair of single


quotes or double quotes. "Hi", "8.5", `hello' are all strings.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 18 Prepared By Mrs. Bini Charles, TIST
• Multi-line strings are written within a pair of triple quotes, ``` or """. The following
is an example of a multi-line string:
• """ this is a multiline

String example """

• The strings ' ' and " " are called empty strings.

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.
• In addition to functions, the math module also has the values of the constants π and e. 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)

>>> import math

>>> math.pi

3.141592653589793

>>> math.e

2.718281828459045

>>> math.sqrt(3)

1.7320508075688772

UCEST105- AlGORITHMIC THINKING WITH PYTHON 19 Prepared By Mrs. Bini Charles, TIST
Data input and output

• Python provides various functions or methods for performing I/O operations.


• To display something on the screen, Python uses the method print. It just prints whatever is given
inside the quotes.
• print()

UCEST105- AlGORITHMIC THINKING WITH PYTHON 20 Prepared By Mrs. Bini Charles, TIST
• input()

• Type conversion functions

ü Type conversion functions to convert values from one data type to another.

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

>>> 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'>

What is mean by Functions

ü 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:

1. Built-in function and


2. User-defined functions.

ü Built-in functions are those that are provided by the interpreter itself. These include I/O
functions, mathematical functions, etc.
UCEST105- AlGORITHMIC THINKING WITH PYTHON 21 Prepared By Mrs. Bini Charles, TIST
ü 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.

STRING

n Python, a string is a sequence of characters enclosed in quotes. Strings can be


defined using either single quotes ('...'), double quotes ("...") for single line
string., or triple quotes ('''...''' or """...""") for multiple line string.

Function/Method Description Example Output


len(s) Returns the len("Hello") 5
length of the
string s.

s.upper() Converts all "hello".upper() "HELLO"


characters to
uppercase.

s.lower() Converts all "HELLO".lower() "hello"


characters to
lowercase.

s.title() Converts the "hello world".title() Hello World


first character of
each word to
uppercase.

str.strip() Removes leading " Hello ".strip() Hello


and trailing
whitespace.

str.replace() Replaces "Hello, World!".replace("World",


Hello, Python!
occurrences of a "Python")
substring.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 22 Prepared By Mrs. Bini Charles, TIST
str.find() Returns the index "Hello, 7
of a substring, or - World!".find("World")
1 if not found.

Concatenates two concat("Hello, ", "World!") Hello, World!


str.concat() strings directly

Returns the 2
count() "Hello, World!".count("o")
number of
occurrences of a
substring

Operators in Python

Python language supports the following types of operators.

i. Arithmetic Operators

ii. Comparison (Relational) Operators

iii. Assignment Operators

iv. Logical Operators

v. Bitwise Operators

vi. Membership Operators

vii. Identity Operators

UCEST105- AlGORITHMIC THINKING WITH PYTHON 23 Prepared By Mrs. Bini Charles, TIST
i. Arithmetic Operators

UCEST105- AlGORITHMIC THINKING WITH PYTHON 24 Prepared By Mrs. Bini Charles, TIST
ii. Comparison (Relational) Operators

iii. Assignment operator (=)

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

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

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

UCEST105- AlGORITHMIC THINKING WITH PYTHON 25 Prepared By Mrs. Bini Charles, TIST
iv. Logical Operators

• AND (&&): Returns true if both operands are true.

• Example: true && true results in true.

• OR (||): Returns true if at least one of the operands is true.

• Example: true || false results in true.

• NOT (!): Reverses the Boolean value of an operand.

• Example: !true results in false.

• Truth Table for ‘Logical OR’, ‘Logical AND’

UCEST105- AlGORITHMIC THINKING WITH PYTHON 26 Prepared By Mrs. Bini Charles, TIST
• Truth Table for ‘Logical NOT’

V. Bitwise Operators

Python bitwise operators are used to perform bitwise calculations on integers. The integers are first
converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the
name bitwise operators. The result is then returned in decimal format.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 27 Prepared By Mrs. Bini Charles, TIST
Let’s take a number 14.
Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8 bit) 14 =
(00001110) 2
Then 14 << 1 will shift the binary sequence 1 position to the left side.
Like,

Pictorial Explanation

Python Bitwise Right Shift


Shifts the bits of the number to the right and fills 0 on voids left( fills 1 in the case of a negative number)
as a result. Similar effect as of dividing the number with some power of two.
Example 1:
a = 10 = 0000 1010 (Binary) a >> 1 = 0000 0101 = 5
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
Python Bitwise Left Shift
Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of
multiplying the number with some power of two.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 28 Prepared By Mrs. Bini Charles, TIST
Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40

EXPRESSIONS
An expression is defined as a combination of constants, variables and operators. An expression always
evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone
operator is not an expression. Some examples of valid expressions are given below.
(i) num – 20.4 (ii) 3.0 + 3.14
(iii) 23/3 -5 * 7(14 -2) (iv) "Global"+"Citizen"

Precedence of Operators

So far we have seen different operators and examples of their usage. When an expression contains
more than one operator, their precedence (order or hierarchy) determines which operator should
be applied first. Higher precedence operator is evaluated before the lower precedence operator. In
the following example, '*' and '/' have higher precedence than '+' and '-'.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 29 Prepared By Mrs. Bini Charles, TIST
Note:

a) Parenthesis can be used to override the precedence of operators. The expression within () is
evaluated first.

b) For operators with equal precedence, the expression is evaluated from left to right.

Example 01: How will Python evaluate the following expression?

20 + 30 * 40

Solution:

#precedence of * is more than that of +

= 20 + 1200 #Step 1

= 1220 #Step 2

Example 02: How will Python evaluate the following expression?

(20 + 30) * 40

Solution:

= (20 + 30) * 40 # Step 1

#using parenthesis(), we have forced precedence of + to be more than that of *

= 50 * 40 # Step 2

= 2000 # Step 3

Example 03: How will the following expression be evaluated?

15.0 / 4.0 + (8 + 3.0)

Solution:

= 15.0 / 4.0 + (8.0 + 3.0) #Step1

= 15.0 / 4.0 + 11.0 #Step 2


= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

UCEST105- AlGORITHMIC THINKING WITH PYTHON 30 Prepared By Mrs. Bini Charles, TIST
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, com- mas, 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:

Practice Questions

1. Write a Python program to perform the sum of two numbers.


2. Write a Python program to find the quotient of two numbers.
3. Write a Python program to calculate the area of a circle given its radius.
Hint: area = π * r^2 (use π ≈ 3.14)
4. Write a Python program to determine the perimeter (circumference) of a circle given its
radius. Hint: perimeter = 2 * π * r
5. Write a Python program to find the area of a rectangle given its length and width.
Hint: area = length * width
6. Write a Python program to calculate the volume of a cube given the length of its side.
Hint: volume = side^3
7. Write a Python program to find the area of a triangle given its base and height.
Hint: area = 0.5 * base * height
8. Write a Python program to perform the sum of three numbers.
Hint: sum = a + b + c

UCEST105- AlGORITHMIC THINKING WITH PYTHON 31 Prepared By Mrs. Bini Charles, TIST
9. Write a Python program to convert Celsius to Fahrenheit.
Hint: fahrenheit = (celsius * 9/5) + 32
10. Write a Python program to convert Fahrenheit to Celsius.
Hint: celsius = (fahrenheit - 32) * 5/9
11. Write a Python program to calculate the average of three numbers.
Hint: average = (a + b + c) / 3
12. Write a Python program to calculate the area of a trapezoid given its bases and height.
Hint: area = 0.5 * (base1 + base2) * height
13. Write a Python program to calculate the simple interest given principal, rate, and time.
Hint: interest = (principal * rate * time) / 100
14. Write a Python program to determine the distance between two points (x1, y1) and (x2, y2).
Hint: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)

UCEST105- AlGORITHMIC THINKING WITH PYTHON 32 Prepared By Mrs. Bini Charles, TIST

You might also like