0% found this document useful (0 votes)
5 views128 pages

Python Problem-Solving Strategies

Uploaded by

athulyam800
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views128 pages

Python Problem-Solving Strategies

Uploaded by

athulyam800
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

ALGORITHMIC THINKING

WITH PYTHON
► Course Code: UCEST105
► Course Type :Theory
► Teaching Hours/Week (L: T:P: R) 3:0:2:0
► Credits 4
► ESE Marks 60
► CIE Marks 40 Prepared by
SUMEERA K
GECK
Module-I
► 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.
INTRODUCTION

• A computer is a very powerful and versatile machine capable of performing


various tasks

• A computer performs many tasks exactly in the same manner as it is told to do.

• This places responsibility on the user to instruct the computer in a correct and a
precise manner

• In order to instruct a computer correctly, the user must have a clear understanding
of the problem to be solved.
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.
Well-defined Problems Ill-defined Problems

1. Clear goals and Objectives Unclear and Vague goals and Objectives

2. Specific, measurable outcomes Multiple , conflicting outcomes

3. Well defined constraints Ambiguous or uncertain constraints

4. Relevant data available Insufficient data available

5. Single , Identifiable Solution Multiple possible solutions

6. Logical, step by step approach Requires creative, iterative approach

7. Ex :Solution of a particular Ex: Paint a beautiful picture


mathematical equation
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:

Mathematical Equation:
■ Problem: Solve the equation 2x+3=7.

Crossword Puzzle:
■ Problem: Complete a standard crossword puzzle.

Recipe Execution:
■ Problem: Bake a chocolate cake using a provided recipe.
Ill-Defined Problems:
These problems are ambiguous, lack clear criteria for solutions, and often have multiple
possible solutions.

Here are three examples:

Designing a Sustainable City:


■ Problem: How can we design a sustainable city for the future?

Writing a Novel:
■ Problem: Write a compelling novel that appeals to a broad audience.

Resolving Workplace Conflict:


■ Problem: Resolve a conflict between two team members in the workplace.
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 STRATEGIES

• Solving problems involves, first clearly identifying the issue.


• O n c e the problem is identified, a problem-solving strategy c a n b e applied.
• A problem-solving strategy is a plan used to overcome a challenge or find a
solution.
• Different strategies ha ve distinct action plans.
• "Trial a n d error" is a c o m m o n problem-solving strategy.
• Each strategy includes steps that guide you in resolving a problem.
• Effective problem-solving requires identifying the problem, choosing the
right approach, a n d following a plan tailored to the issue.
5 STEPS TO EFFECTIVE PROBLEM SOLVING

1. Define the problem

2. Brainstorm possible solutions

3. Evaluate the solutions

4. Implement the solution

5. Monitor and adjust


UNDERSTANDING MULTIPLE PROBLEM SOLVING STRATEGIES
Understanding multiple problem solving strategies is crucial as it allows for adaptability
and flexibility, ensuring that one can choose the most efficient method for any given
situation.
By knowing several strategies, one can quickly switch tactics when one method does
not work, increasing the chances of finding a successful solution.
Some benefits are as follows :
Adaptability: Different problems require different approaches. Understanding 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.
What Are Problem-Solving Strategies?

• A problem-solving strategy is essentially a plan of action to find a solution.

• There are several strategies you can use, each with its own method and application.
Below are some of the most common problem-solving strategies:

1. Trial and Error


2. Heuristics
3. Means-Ends Analysis
4. Backtracking
Trial and Error: This strategy involves trying different solutions and learning from
mistakes until the correct one is found. It's practical when you have no clear path to the
solution and need to explore various options.

Heuristics: Heuristics are mental shortcuts or "rules of thumb" that simplify decision-
making and problem-solving. These strategies aim for quick, practical solutions that are
"good enough" rather than perfect.

Means-End Analysis: This strategy involves breaking down a problem into smaller,
manageable parts (means) and addressing each part to reduce the difference between the
current state and the goal state (end). It's useful for complex problems with clear goals.

Back tracking: Backtracking is used when solving problems that involve exploring multiple
options. If a chosen path doesn’t work, you backtrack to the previous step and try a different
approach, ensuring that all possibilities are considered.
1. Trial and Error
• A trial-and-error approach to problem-solving involves trying a number of
different solutions and ruling out those that do not work.
• This approach can be a good option if you have a very limited number of options
available.
• Using trial and error, one has to try different solutions until the problem is solved.

Steps :

1. Identify the problem


2. Attempt a possible solution Evaluate the outcome
3. Check if the solution worked.
4. Repeat– If the solution failed, try a different one.
When to Use the Trial and Error Method:
• Unfamiliar Problems: When you’re dealing with a problem you’ve never
encountered before and don’t know the exact solution.
• Limited Information: When there isn’t enough information available to make an
informed decision.
• Creative Problem-Solving: When you want to explore different possibilities and
don’t mind trying out several options.

When Not to Use It:


• Time-Sensitive Problems: If you need a quick solution, Trial and Error might be too
slow, as it can take many attempts to find the right answer.
• Complex Problems: For very complex problems, other methods might be more
efficient.
EXAMPLES

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. say the problem is that your Wi-Fi isn’t working. You might try different things
until it starts working again, like restarting your modem or your devices until you
find or resolve the problem. When one solution isn’t successful, you try another
until you find what works.

3. If your child always stays up past their bedtime, you might try different solutions—
a visual clock to remind them of the time, a reward system, or gentle
punishments — to find a solution that works.
• Learning to Ride a Bicycle:
• Example: When learning to ride a bike, you might fall several times before figuring out
how to balance and steer properly. Each attempt helps you learn what works and what
doesn’t, leading to success.
• Solving a Puzzle:
• Example: If you’re putting together a jigsaw puzzle, you might try several pieces in a
spot before finding the one that fits. You test each piece until you find the correct one.
• Cooking Without a Recipe:
• Example: If you're cooking a dish without a recipe, you might experiment with adding
different amounts of spices or ingredients until you achieve the desired taste. You keep
adjusting based on the results of each attempt.
• Finding the Right Tool:
• Example: When assembling furniture, you might try several tools or screws to see
which one fits properly. You continue testing until you find the one that works.
Heuristics

• Heuristics are mental shortcuts or rules of thumb that simplify decision-making


and problem solving.

• They are useful when a quick solution is needed, when the problem is complex, or
when full information is unavailable.

• While heuristics can lead to errors, they are often effective in everyday situations.
Characteristics of Heuristics:

•Simplification: Heuristics simplify complex problems, making them easier


to tackle.

•Speed: They provide quicker solutions by cutting down on the time and
effort needed.

•Satisfactory Results: Heuristics aim for a "good enough" solution rather


than a perfect one, which is often sufficient in practical situations.
Steps in Using Heuristics
Recognize the Problem:
► Understand the problem and what you need to achieve. Identify if a heuristic
approach is appropriate.
Choose an Appropriate Heuristic:
► Select a rule of thumb or shortcut that applies to the situation. Consider which
heuristic might lead to a quick and reasonable solution.
Apply the Heuristic:
► Use the chosen heuristic to guide your decision-making or problem-solving process.
This might involve making an educated guess, simplifying the problem, or using
past experiences.
Evaluate the Outcome:
► Assess whether the heuristic led to a satisfactory solution. If it did, great! If not, you
might need to try a different heuristic or combine several to get a better result.
When to Use Heuristics
• Everyday Decisions: When you need quick answers to routine problems.
• Complex Problems: When a perfect solution is impractical, and you need a
workable answer fast.
• Uncertain Situations: When there’s limited information or too many variables to
consider, and a best guess is your best bet.

When Not to Use Heuristics:


• Critical Decisions: In situations where accuracy is crucial, and the consequences of a
mistake are severe, you might need a more thorough and analytical approach.
• Highly Detailed Problems: When every detail matters and a precise solution is
required, heuristics may oversimplify the issue.
Use Cases:

Shopping: Choosing a product based on brand reputation rather than


comparing every option.
Navigation: Following the general direction toward your destination instead of using a
detailed map.
Medical Diagnosis: Doctors using common symptoms to make an initial
diagnosis before conducting detailed tests.
Stock Investment: Investors using past trends to make decisions on buying or selling
stocks.
Job Interviews: Hiring managers quickly assessing candidates based on first
impressions or resumes.
BACKTRACKING

► The Backtracking method is a problem-solving strategy that involves exploring


possible solutions to a problem by building them incrementally, step by step. If you
reach a point where the current path doesn't lead to a solution, you backtrack
—go back to the previous step and try a different path.

What is the Backtracking Method?


Definition: Backtracking is a method where you try to solve a problem by
exploring all possible options. If you find that a certain option doesn’t lead to a valid
solution, you undo (or "backtrack") that choice and try the next option.

Purpose: The goal is to find the correct solution by systematically exploring all
possibilities, while discarding paths that don’t work.
Steps in the Backtracking Method:
Identify the Problem and Constraints:
► Clearly understand the problem and any constraints (rules or limitations) that need to
be followed.
Start with an Initial Decision:
► Begin by making an initial choice or taking the first step in your solution process.
Explore Further:
► Move forward by making the next decision or taking the next step. Continue to build
your solution incrementally.
Check for Validity:
► After each step, check if the current path is valid and satisfies the problem’s
constraints. If it’s invalid, you need to backtrack.
•Backtrack if Necessary:
► If you reach a point where the current path doesn’t work, undo the last step (backtrack)
and try a different option. This might involve going back multiple steps until you find a
valid path.
•Continue Until Solution is Found:
► Repeat the process of exploring and backtracking until you either find a solution
that meets all the criteria or determine that no solution exists within the given
constraints.
When to Use the Backtracking Method
Puzzles and Games: In puzzles like Sudoku, N-Queens, or crosswords where you
need to place elements in a grid under certain constraints.
Decision-Making: In scenarios where each decision builds on the previous one, and
you need to ensure that each step is valid before proceeding.

When Not to Use Backtracking:


Simple Problems: If the problem has a straightforward solution without multiple
paths, backtracking might be unnecessary and overcomplicated.
Time-Sensitive Situations: Backtracking can be time-consuming, especially if
there are many possible paths to explore. In time-sensitive situations, a more direct
approach might be better.
Use Cases

Maze Solving: Navigating through a maze by choosing paths, and backtracking if a


path leads to a dead end.

Sudoku: Filling in numbers, and backtracking when a mistake is realized.

Travel Planning: Planning a multi-city trip, backtracking to change a route if it’s not
feasible or too expensive.
MEANS-END ANALYSIS

► Means-End Analysis is a problem-solving strategy where you break down the


problem into a series of steps (means) to reach a desired outcome (end). Here’s
how it works:

What is Means-End Analysis?


► Means-End Analysis involves identifying the current state (where you are now) and
the goal state (where you want to be). The key idea is to reduce the difference
between these two states by applying specific actions or steps (means) that bring you
closer to the goal.
Steps in Means-End Analysis
Identify the Goal (End):
► Clearly define what you want to achieve. This is the end state you are aiming for.
Assess the Current State:
► Understand your current position or condition relative to the goal. Identify the gap or
difference between where you are and where you want to be.
Identify the Differences:
► Determine the differences between the current state and the goal state. These
differences highlight what needs to be changed or achieved to reach the goal.
Select and Apply an Action (Means):
► Choose an action or step that will reduce the difference between the current state and
the goal state. This action is a means to bring you closer to your goal.
•Evaluate and Repeat:
► After applying the action, reassess the new current state. If the goal hasn’t been fully
achieved, repeat the process by identifying the next difference and applying another
action until the goal is reached.
Use Cases:
Project Management: Breaking down a large project into smaller tasks and setting
milestones to reach the final goal.

Medical Treatment Plans: Doctors setting treatment milestones (e.g., reducing pain,
improving mobility) to achieve the final goal of full recovery.

Chess Strategy: Players determining the end goal (checkmate) and working
backward to create a sequence of moves to reach it.

Educational Goals: Students setting long-term goals (e.g., graduating) and breaking
them down into semester-wise targets and daily study plans.
Comparative Summary
Trial and Error:
Efficiency: Often inefficient due to the potentially large number of steps.
Best for: Simple problems or when no clear solution path is available.
Heuristics:
Efficiency: More efficient than Trial and Error but less reliable.
Best for: Quick decisions where perfect accuracy is not essential.
Backtracking:
Efficiency: Moderately efficient, especially in structured problems.
Best for: Problems where multiple paths can be explored and retracted, like puzzles
•Means-Ends Analysis:
• Efficiency: Generally efficient due to systematic problem breakdown.
• Best for: Complex problems that can be decomposed into smaller sub-problems with a
clear path to the goal.
Conclusion

► The efficiency of these problem-solving strategies varies based on the nature of the
problem:
Trial and Error can be the least efficient, with a potentially high number of
steps.
Heuristics are faster but may not always lead to the optimal solution.
Backtracking is efficient in structured environments where wrong paths can be
retraced.
Means-Ends Analysis is often the most efficient for complex, multi-step
problems.

► Understanding the problem type and applying the appropriate strategy will lead to
better problem-solving efficiency.
PROBLEM SOLVING PROCESS

Problem Solving is the sequential process of analyzing information


related to a given situation and generating appropriate response
options.
Basic Model of a Computer
• In today’s digital era, the computer has become an indispensable part of our life.
• Computers are potent tools for solving problems across diverse disciplines
• Whether the problem arises from the real world or an abstract concept, a
systematic approach is essential for finding solutions. Since computers are our
tools for problem solving, it's crucial to understand how they process
information.
• Typically, a computer with a CPU (Central Processing Unit) follows a model it
takes input, processes it, and then produces output
Computer As A Model Of Computation

• In problem-solving, we apply the model of computation where we start with some


input information, process it, and produce the desired output as the solution.

• While this basic model works well for simple problems, more complex problems
often require multiple iterations of the input/process/output stages.

• These iterations produce intermediate results that help solve parts of the problem
before reaching the final solution.

• The essence of problem-solving lies in how we handle the "process" part of this
model. Therefore, understanding and mastering this stage is crucial.
Steps involved in problem solving

• Understanding the problem

• Formulating a model

• Developing an algorithm

• Writing the program

• Testing the program

• Evaluating the solution


Understanding The Problem

The first step in solving any problem is to ensure you fully understand it. This means
identifying the data provided, understanding what it represents, and knowing the
expected output.

Key Questions to Consider:

• Input Data: What data is available, and in what format?


• Missing Information: Is any data missing? How should it be handled?
• Output Requirements: What needs to be produced, and in what format?
• Processing: What operations need to be performed on the data?
Example:

If you're asked to calculate the average grade for a class

Input: Some grades might be numerical (e.g., 85, 90) and others in letter form (e.g., A-,
C+).
Missing Data: Some students might not have grades due to absence.
Output: The result could be a number, letter grade, or graph.

To solve the problem, we must first understand the format of the grades .
The grades could be numbers ranging from 0 to 100 (e.g., 73 or 73.42), or they could be
letter grades like A to F. The format matters because different types of data (numbers vs.
letters) require different methods of calculation.
• We also need to address missing grades.
If a student doesn’t have a grade, how should we handle it?
For example, if a student was absent, do we: Include them with a grade of 0?
Exclude them from the average?

• Next, we need to decide on the output format.


Should the average be a: Whole number (e.g., 80), Real number (e.g., 79.5), or
Letter grade?

• Lastly, it's important to understand the processing involved. What calculations or


operations are needed to process the data? This will guide how we approach solving
the problem.
Formulating A Model

Once the problem is understood, the next step is to figure out how to process the
available data. This often involves breaking the problem into smaller, more manageable
parts and using mathematical formulas to get the desired result.

Formulating a model involves creating a formula or approach to process the input data.
This model helps us compute the result accurately. If no standard formula exists, we must
develop one.

● Example - 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 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.
s
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. 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
Step 6: End
Pseudo code

1. Start

2. Input Number1

3. Input Number2

4. Sum=Number1 +Number2

5. Output Sum

6. End
Flowchart
Writing the Program

Once the algorithm is defined, the next step is to transform the algorithm into a set of
instructions that can be understood by the computer. Writing a program is often called
"coding" or “implementing an algorithm”.
Steps to Writing a Program

1. Understand the Algorithm:


• Ensure that you have a clear and precise algorithm outlining the steps to solve
the problem.
• The algorithm should include all necessary inputs, operations, and outputs.

2. Translate Algorithm to Pseudocode:


• Before coding, convert the algorithm into pseudocode, which is a simplified,
human-readable representation of the steps.
• Pseudocode helps in visualizing the logic without worrying about syntax.
3. Implement in Code: Translate the pseudocode into a specific programming
language. This involves:
• Defining Variables: Initialize variables as needed.
• Input Handling: Write code to capture user inputs or read data.
• Processing Logic: Implement the core algorithm steps in code.
• Output Handling: Display or return results to the user.

4. Testing and Debugging:


• After writing the code, test it with various inputs to ensure it works as expected.
• Debug any issues or errors that arise during testing.

Compiling is the process of converting a program into instructions that can be understood
by the computer.
Sample Code :

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum = num1 + num2

print("Sum:", sum)
Testing the Program
Once a program has been written and compiled, the next critical step is to ensure that it
performs the intended task correctly.
Testing the program involves running it with various inputs to verify its accuracy and
reliability.

Key Steps in Testing the Program

Running the Program: Running a program is the process of executing the compiled
code on a computer. If the program runs correctly, the expected output should be
displayed.

Testing for All Cases: It's possible that a program may work correctly for some inputs
but fail for others. Therefore, a program should be tested with a variety of input data to
cover all possible scenarios.
Handling Errors: If the output is incorrect,
it could be due to:
• The algorithm not being properly implemented in the program.
• A flaw in the algorithm itself, which does not account for certain situations.
• Bugs: : Bugs are errors in a program that cause it to produce incorrect or
undesirable results.

Bugs can occur due to:


• Misinterpretation of the algorithm.
• Errors in the sequence of instructions.
• Oversights that cause the program to handle specific input cases incorrectly.

Debugging: Debugging is the process of finding and fixing errors (bugs) in the
program. It involves systematically testing different cases to locate the issues and
correcting them.
Evaluating The Solution

After a program produces results, it is important to evaluate those results in the context
of the original problem. This step ensures that the output is not only correct but also
meaningful and in the required format.

• Reconsider the Original Problem: Ensure the program’s output aligns with the
original problem and is in the correct format.

• Interpreting the Results: Present the results in a clear and meaningful way that aids
decision-making, using tools like charts if needed.

• Adjusting the Solution: If necessary, add more steps or data to fully solve the problem
or improve the solution’s effectiveness.
• Efficiency Considerations: Evaluate the program’s performance and make
improvements if it’s too slow or uses too many resources.

• User Responsibility: It’s up to the user or programmer to ensure the solution truly
solves the problem; further adjustments may be needed.
EXAMPLE:-The Discriminant calculator

1. Understanding the problem: Here we formally define the problem by specifying


the inputs and output.

Input: The three coefficients a, b and c of the quadratic equation


Output: The discriminant value D for the quadratic equation

2. Formulating a model: Develop a mathematical model for the solution, that is


identify the mathematical expression for the quadratic equation discriminant D:

D = b² - 4ac
3. Developing an algorithm:

A possible algorithm for discriminant problem

STEP 1: Start

STEP 2: Read (a,b,c)

STEP 3: d = b∗b−4∗a∗c

STEP 4: Print (d)

STEP 5: Stop
4. Writing the program:

The Python program to calculate the discriminant :

#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. Testing the program: You create a test suite similar to the one shown in
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

• 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.


PROGRAMMING LANGUAGES

• Programming languages are used to write programs that are 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.
• Assembly language:- falls in between machine language and high-level language. It is
similar to machine language, but easier to write code because it allows the
programmer to use symbolic names (like ADD, SUB) for operations called mnemonic
codes that are much easier to remember.

Machine languages and assembly languages are also called low level languages.

• 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, Pascal, Java, Python etc. 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.
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,it reads the source code line-by-line, converts it into machine
code, executes the line, and then proceeds to the next line.
Differentiate between Compiler and Interpreter.
Python: An Overview

Python is a high-level, interpreted programming language invented in the late 1980s by


Guido van Rossum. It is widely known for its simplicity and readability, which makes it
ideal for beginners. Python is versatile, being used for web development, data analysis,
automation, machine learning, and more. It is popular for its beginner-friendly syntax
and the large number of libraries available for various applications.
APPLICATIONS OF PYTHON

Python is a general purpose programming language. It is widely applied in various


fields.

● Data Science : Python libraries like Numpy, Pandas, and Matplotlib are used for data
analysis and visualization.
● Web Applications : Python frameworks like Django, and Pyramid, make the
development and deployment of Web Applications easy.
● Desktop GUI Applications
● Software Development
● Scientific and Numeric computations
● Business Applications
● Audio or Video based Applications.
Execution Modes

There are two ways to use the Python interpreter:


a) Interactive mode
b) Script mode

Interactive mode allows execution of individual statement instantaneously. Whereas,


Script mode allows us to write more than one instruction in a file called Python source
code file that can be executed.
Interactive Mode

• To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly. As soon as we press enter, the interpreter executes the statement and
displays the result(s)

• Working in the interactive mode is convenient for testing a single line code for instant
execution. But in the interactive mode, we cannot save the statements for future use
and we have to retype the statements to run them again.
Script Mode

In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it. Python scripts are saved as files where file name has extension
“.py”. By default, the Python scripts are saved in the Python installation folder. To
execute a script, we can either:

a) Type the file name along with the path at the prompt. For example, if the name of the
file is [Link], we type [Link]. We can otherwise open the program directly
from IDLE
b) While working in the script mode, after saving the file, click [Run]->[Run Module]
from the menu
Feature Interactive Mode Script Mode
Line by line, immediate Entire program executed from a
Execution
feedback file

Experimentation, quick tests, Developing applications,


Purpose
debugging persistent programs

Persistence Commands are not saved Code is saved in a file for reuse

Output for each line displayed Output displayed after entire script
Output
immediately execution

Easy to edit and manage code in a


Code Editing Tedious for multiple lines
file
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 :
1. Keyword (Reserved words)

► Keywords are the reserved words in Python.


► We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
► In Python, keywords are case sensitive.
► There are 33 keywords in Python 3.7. This number can vary slightly over
the course of time.

All the keywords except True, False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.
2. Identifiers

Just as identity refers to a characteristic that distinguishes a person, the same principle is a
python identifier, a token in python. In Python, an identifier is a name given to a Class,
Function, or Variable. It aids in distinguishing one entity from others.

Characteristics of Python Identifier


•The initial letter of the identifier should be any letter or underscore (_).
•Upper and lower case letters have distinct characteristics.
•Except for the initial letter, any digit from 0 to 9 can be part of the identification.
•It shouldn’t be used as a keyword
•Except for the underscore (_), an identifier cannot contain any special characters.
•Identifiers can be as long as you want them to be.
•Case matters when it comes to identifier names. Myself and myself, for example, are not
the same thing.
3. Operators
An operator is used to perform specific mathematical or logical operation on values.
Operands are the variables and objects to which the computation is applied. There are 7
different operators.

i)Arithmetic Operators
It performs all the mathematical calculations. Here are a few of them:
•( + ) –Addition-Adds the two numeric values on either side of the operator
This operator can also be used to concatenate two strings on either side of the
operator

( – ) –Subtraction- Subtracts the operand on the right from the operand on the left

•(✖️) –Multiplication-Multiplies the two values on both side of the operator


Repeats the item on left of the operator if first
operand is a string and second operand is an
integer value
•(➗) –Division-Divides the operand on the left by the operand on the right and returns
the quotient

•(%)-Modulus- Divides the operand on the left by the operand on the right and returns
the remainder

•(//) Floor Division-Divides the operand on the left by the operand on the right and
returns the quotient by removing the decimal part. It is sometimes
also called integer division.

•(**)-Exponent-Performs exponential (power) calculation on operands. That is, raise


the operand on the left to the power of the operand on the right
ii) Relational Operators

Relational operator compares the values of the operands on its either side and
determines the relationship among them.
Operator Operation Description
If the values of two operands are equal, then the condition is True,
== Equals to
otherwise it is False
If values of two operands are not equal, then condition is True,
!= Not equal to
otherwise it is False
If the value of the left-side operand is greater than the value of the
> Greater than
right side operand, then condition is True, otherwise it is False

If the value of the left-side operand is less than the value of the
< Less than
right side operand, then condition is True, otherwise it is False
If the value of the left-side operand is greater than or equal to the
Greater than
>= value of the right-side operand, then condition is True, otherwise it
or equal to
is False
Less than or If the value of the left operand is less than or equal to the value of
<=
equal to the right operand, then is True otherwise it is False
iii) Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.

Operator Description
= Assigns value from right-side operand to left side operand
It adds the value of right-side operand to the left-side operand and
+= assigns the result to the left-side operand Note: x += y is same as x
=x+y
It subtracts the value of right-side operand from the left-side
-= operand and assigns the result to left-side operand Note: x -= y is
same as x = x - y
It multiplies the value of right-side operand with the value of left-
*= side operand and assigns the result to left-side operand Note: x *= y
is same as x = x * y
iv) Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are
to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on either side. Every value is logically either
True or False.
Every value is logically either True or False. By default, all values are True except
None, False, 0 (zero), empty collections "", (), [], {}, and few other special values.
v) Membership Operators
Membership operators are used to check if a value is a member of the given sequence or
not.
Operator Description
Returns True if the variable/value is found in the specified sequence
in
and False otherwise
Returns True if the variable/value is not found in the specified
not in
sequence and False otherwise

vi) Identity Operators


Identity operators are used to determine whether the value of a variable is of a certain type
or not. Identity operators can also be used to determine whether two variables are referring
to the same object or not. There are two identity operators.
Operator Description

Evaluates True if the variables on either side of the operator point


is towards the same memory location and False otherwise. var1 is var2
results to True if id(var1) is equal to id(var2)

Evaluates to False if the variables on either side of the operator point


is not to the same memory location and True otherwise. var1 is not var2
results to True if id(var1) is not equal to id(var2)
vii. Bitwise Operator
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.
EXAMPLES
a = 10 # Binary: 1010
a = 10 # Binary: 1010
b = 4 # Binary: 0100
b = 4 # Binary: 0100
result = a ^ b
result = a & b
print("Bitwise XOR of a and b:", result)
print("Bitwise AND of a and b:",result)
Out put: Bitwise XOR of a and b: 14
Out put: Bitwise AND of a and b: 0
x = 5 # Binary: 0000 0101
a = 10 # Binary: 1010
result = ~x
b = 4 # Binary: 0100
print("Bitwise NOT of X:", result)
result = a | b
print("Bitwise OR of a and b:",result)
Out put: Bitwise NOT of X: -6
Out put: Bitwise OR of a and b: 14
x = 5 # Binary: 0000 0101 x=10
result = x << 2 print(bin(x))
print("Left shift of X by 2:",result)
Out put: 0b1010
Out put: Left shift of X by 2: 20

x = 20 # Binary: 0001 0100


result = x >> 2
print("right shift of X by 2:",result)

Out put: right shift of X by 2: 5


PRECEDENCE OF OPERATORS
Evaluation of the expression is based on precedence of operators. When an expression
contains different kinds of operators, precedence determines which operator should be
applied first. Higher precedence operator is evaluated before the lower precedence
operator.

Note:
• Parenthesis can be used to override the precedence of operators. The expression
within () is evaluated first.
• For operators with equal precedence, the expression is evaluated from left to right.
How will Python evaluate the following expression?

• 20 + 30 * 40

• 20 - 30 + 40

• (20 + 30) * 40

• 15.0 / 4 + (8 + 3.0)
4. Literals

Literals, tokens in Python, are data elements with a fixed value. Literals return a value
for an object of the specified type. Python supports a variety of literals:
•String Literals
•Numeric Literals. These are further of three types, integer, float, and complex literals.
•Boolean Literals
•Literal Collection
Lists, tuples, dictionaries, and sets are all examples of literal collections in Python.
5. Punctuators

Punctuators are tokens in python employed to put the grammar and structure of
syntax into practice. Punctuators are symbols that are used to structure programming
sentences in a computer language. Some commonly used punctuators are: ‘, ‘ ,#, \ ,( ) ,{
},[ ] ,@ ,: , =
VARIABLES
A variable in a program is uniquely identified by a name (identifier).Variables are
nothing but named reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.

• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
• Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
Creating Variables In Python
• creating a variable is straightforward. You assign a value to a variable using the equal
sign =.
• Examples:
• age = 25
• name = "John"
• In the first line, age is a variable that stores the number 25.
• In the second line, name is a variable that stores the string "John".
• Python automatically detects the data type (number, string, etc.), so you don’t
have to declare the type.
Using Variables

Once a variable is created, you can use it throughout your program.

For example:

print(age)
print(name)

You can also combine variables with text:


print("My name is", name, "and I am", age, "years old.")

This will output: My name is John and I am 25 years old.


Changing Variable Values

Variables in Python are dynamic, meaning you can change their values after they are
created:

python
Copy code
age = 26
print(age)

Now, the variable age holds the value 26.


Variable Naming Rules

There are some important rules to follow when naming variables in Python:

1. Variable names must start with a letter or an underscore _.


2. They cannot start with a number.
3. Only letters, numbers, and underscores are allowed in variable names.
4. Variable names are case-sensitive (Age and age are different).
5. A variable name cannot be a reserved Python keyword (e.g., for, while, if).
Legal Variable Names

• Starting with a letter or underscore:


 Age

 Name

 Temp

 my_variable

• Containing letters, numbers, and underscores (but not starting with a number):
 age2 data_1
 user_name
 totalAmount
Illegal Variable Names

•Starting with a number:


 1age
 2nd_place

•Containing spaces:
 my variable

•(Use underscores instead, like my_variable)

•Using special characters (except for underscores):


 user-name
 total$amount
 @user
Data types

• A data type in Python defines the type of value a variable can hold and
determines what operations can be performed on that data.
• It specifies whether the data is an integer, floating-point number, string, or
another type.
• Python is a dynamically-typed language, meaning you don't need to specify the data
type while declaring a variable; Python automatically assigns the data type
based on the value assigned
1. Number

Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
[Link] Data Type in Python

The boolean data type represents one of two values: True or False.

Boolean values are often used in conditional statements to control the flow of a
program based on whether a condition is true or false.

Boolean Values:
• True
• False
3. Sequence
A Python sequence is an ordered collection of items, where each item is indexed by
an integer. The three types of sequence data types available in Python are Strings, Lists
and Tuples.

(A)String: String is a group of characters. These characters may be alphabets, digits or


special characters including spaces. String values are enclosed either in single
quotation marks (e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”). The quotes
are not a part of the string, they are used to mark the beginning and end of the string
for the interpreter.
For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"

We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2
• Single-Line Strings: Can use single or double quotes for simple strings.
Example:
name = 'John' # String using single quotes
greeting = "Hello!" # String using double quotes

• Multi-Line Strings: Triple quotes are used for strings spanning multiple lines.
Example:
message = “““This is a
multi-line string.”””

• String Operations:
 Concatenation: Joining strings together using the + operator.
full_name = "John" + " " + "Doe"
# Output: "John Doe“
 Repetition: Repeating a string using the * operator.
repeated = "Hi! " * 3
# Output: "Hi! Hi! Hi! "
(B) List

List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ]. Example

#To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple

Tuple is a sequence of items separated by commas and items are enclosed in parenthesis
( ). This is unlike list, where values are enclosed in brackets [ ]. Once created, we
cannot change the tuple.

Example
#create a tuple
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
4. Set

Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have
duplicate entries. Once created, elements of a set cannot be changed.

Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
5. Mapping

Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.

(A)Dictionary

Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }. Dictionaries permit faster access to data. Every key is
separated from its value using a colon (:) sign. The key : value pairs of a dictionary can
be accessed using the key. The keys are usually strings and their values can be any data
type. In order to access any value in the dictionary, we have to specify its key in square
brackets [ ].
Example

#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1['Price(kg)'])
120
Type Conversion in Python (Type Casting)

Type conversion Type conversion refers to the process of converting the value of one
data type to another.
Python offers two types of type conversions

Implicit Type Conversion (Automatic)


Python automatically converts one data type to another when needed without any user
involvement.

Explicit Type Conversion (Manual)


The user manually converts data from one type to another using built-in functions like
int(), float(), str(), etc.
FUNCTIONS

In programming, the use of function is one of the means to achieve modularity and
reusability. Function can be defined as a named group of instructions that
accomplish a specific task when it is invoked.

Types of functions
PYTHON STANDARD LIBRARY
Python has a very extensive standard library. It is a collection of many built in functions
that can be called in the program as and when required, thus saving programmer’s time
of creating those commonly used functions every time.

Built-in functions
Built-in functions are the ready-made functions in Python that are frequently used in
programs. Let us inspect the following Python program:
#Program to calculate square of a number
a = int(input("Enter a number: ")
b=a*a
print(" The square of ",a ,"is", b)

In the above program input(), int() and print() are the built-in functions. The set of
instructions to be executed for these built-in functions are already defined in the python
interpreter.
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.
EXAMPLES
>>>name = input ('What is your name?- ')
>>>print ('Hello,', name)

What is your name?- John


Hello, John
By default, the input() function accepts only string arguments. However, we can convert
this to a number by using the int() of float() functions.
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. We use the print() function to display the output data to the
(screen).
we can pass several objects () in the print() function by separating them with a comma.

EXAMPLES

• >>>print(100)
100

• >>>num =65
>>>print ('The value of the number is', num)

The value of the number is 65


MODULE
Other than the built-in functions, the Python standard library also consists of a number of
modules. A module is a group of functions. Some commonly used modules are
• math
• random
• statistics

[Link] name : math - It contains different types of mathematical functions. Most of the
functions in this module return a float value.

2. Module name : random - This module contains functions that are used for generating
random numbers.

3. Module name : statistics - This module provides functions for calculating statistics of
numeric (Real-valued) data.
VARIOUS FUNCTIONS IN MATH MODULE

Function Syntax Arguments Returns Example Output


[Link](x) x may be an integer or ceiling value of x >>> [Link](-9.7)
f loating point number -9
>>> [Link] (9.7)
10
>>> [Link](9)
9
[Link](x) x may be an integer or f loor value of x >>> [Link](-4.5)
f loating point number -5
>>> [Link](4.5)
4
>>> [Link](4)
4
[Link](x) x may be an integer absolute value of x >>> [Link](6.7)
or f loating point 6.7
number >>> [Link](-6.7)
6.7
>>> [Link](-4)
4.0
[Link](x) x is a positive integer factorial of x >>> [Link](5)
120
[Link](x,y) x and y may be an x % y with sign of x >>> [Link](4,4.9)
integer or floating 4
point number >>> [Link](4.9,4.9)
0.0
>>> [Link](-4.9,2.5)
2.4
>>> [Link](4.9,-4.9)
0.0
[Link](x,y) x, y are positive integers gcd (greatest common >>> [Link](10,2)
divisor) of x and y 2

[Link](x,y) x, y may be an integer or xy (x raised to the >>> [Link](3,2)


floating point number power y) 9.0
>>> [Link](4,2.5)
32.0
>>> [Link](6.5,2)
42.25
>>> [Link](5.5,3.2)
233.97
[Link](x) x may be a positive integer square root of x >>> [Link](144)
or floating point number 12.0
>>> [Link](.64)
0.8
[Link](x) x may be an integer or f sine of x in radians >>> [Link](0)
loating point number in 0
radians >>> [Link](6)
-0.279
PYQs
[Link] are asked to solve a jigsaw puzzle without a reference picture. How will you solve it
using trial and error method?

[Link] the input "12345", write a Python code snippet to check if it is numeric.

3. Explain how backtracking strategy can be applied to solve Sudoku problem?

[Link] 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.

[Link] are asked to develop new campus management software for your college. How will
you apply Means-Ends Analysis to develop the software?
6. Given the area of a circle. Write a Python program to calculate the radius of the circle
using the math module.

[Link] 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.

8. What will be the result of the following expressions in Python?


i) (50 - 5 * 6) // 4
ii) not (10 < 5) or (5 = = 5)
iii) True and 5

9. Walk through the six problem-solving steps to calculate the area of a circle.
10. What are the basic data types in Python? Provide examples for each.

11. What is the difference between algorithms and heuristics in problem-solving? Provide
an example where heuristics lead to a faster solution than an algorithm.

12. Write a Python program to convert the time input in minutes to hours and minutes.
For example, 85 minutes is 1 hour 25 minutes.
result of the following expressions in Python

0 and 5 → 0 # 0 is falsy, stops and returns 0


'' and 100 → '' # empty string is falsy
True and 0 → 0 # True is truthy, 0 is falsy, returns 0
True and 7 → 7 # both are truthy, returns 7
THANK YOU. MODULE 1 ENDS
HERE

You might also like