Module_-1[1] python ktu
Module_-1[1] python ktu
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.
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.
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.
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
ü 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.”
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.
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.
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.
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,
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.
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.
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.
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.
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.
1. Understand the problem: Here we formally define the problem by specifying the inputs and
output.
D = b2 − 4ac
1. Start
2. Read(a, b, c)
3. d=b∗b−4∗a∗c
4. Print(d)
5. Stop
4. Code the algorithm: The Python program to calculate the discriminant is as follows:
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.
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.
Python Interpreter
i. 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.
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.
Constants
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.