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

mod1 -python.pptx

python

Uploaded by

vidhyapm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

mod1 -python.pptx

python

Uploaded by

vidhyapm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

UCEST105

MODULE 1

15-10-2024

1
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
PROBLEM-SOLVING STRATEGIES
DEFINED
A problem is a situation, question, or thing that causes difficulty, stress, or doubt.
A problem is also a question raised to inspire thought

When people are presented with a problem—whether it is a complex mathematical


problem or a broken printer, how do you solve it?

Before finding a solution to the problem, the problem must first be clearly
identified. After that, one of many problem solving strategies can be applied,
hopefully resulting in a solution.

15-10-2024

2
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
CATEGORIES OF PROBLEM
Problems themselves can be classified into two different categories known as
ill-defined and well-defined problems.
Ill-defined problems represent issues that do not have clear goals, solution paths,
or expected solutions whereas well-defined problems have specific goals, clearly
defined solutions, and clear expected solutions.
Well-Defined Problems are structured, with a clear path and solution.
Ill-Defined Problems are open-ended, ambiguous, and often subjective

15-10-2024

3
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
CATEGORIES OF PROBLEM
Well-Defined Problems are structured, with a clear path and solution.
Eg: Mathematical Equation, Receipe Execution
Ill-Defined Problems are open-ended, ambiguous, and often subjective
Eg: Resolving Workplace Conflict, Writing a Novel

15-10-2024

4
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
PROBLEM-SOLVING PHASES
Phase 1: Understanding the problem.
– What is the unknown? What are the data?
– What is the condition? Is it possible to satisfy the condition? Is the
condition sufficient to determine the unknown? Or is it insufficient?
Or redundant? Or contradictory?
– Draw a figure. Introduce suitable notation.
– Separate the various parts of the condition. Can you write them
down?

15-10-2024

5
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
PROBLEM-SOLVING PHASES
Phase 2: Devising a plan.
– Have you seen it before? Or have you seen the same problem in a
slightly different form?
– Do you know a related problem?
– Look at the unknown! Try to think of a familiar problem having the
same or similar unknown.
– Split the problem into smaller, simpler sub-problems.
– If you cannot solve the proposed problem try to solve first some
related problem. Or solve a more general problem. Or a special case of the
problem. Or solve a part of the problem.

15-10-2024

6
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES:-
PROBLEM-SOLVING PHASES
Phase 3: Carrying out the plan.
– Carrying out your plan of the solution, check each step.
– Can you see clearly that the step is correct?
– Can you prove that it is correct?
Phase 4: Looking back.
– Can you check the result?
– Can you derive the result differently?
– Can you use the result, or the method, for some other problem?

15-10-2024

7
Divya K S, Asst Professor,MITS
PROBLEM-SOLVING STRATEGIES
Problem-solving strategies are essential tools that enable you to effectively tackle a
wide range of challenges by providing structured methods to analyze, understand,
and resolve problems.
These strategies include systematic approaches such as
Trial and Error
Heuristics
Means-Ends Analysis
Backtracking
Each offering unique benefits and applications.

15-10-2024

8
Divya K S, Asst Professor,MITS
IMPORTANCE OF
UNDERSTANDING MULTIPLE
PROBLEM-SOLVING STRATEGIES
Understanding how a variety of problem-solving strategies work is important
because different problems typically require you to approach them in different
ways to find the best solution.
By mastering several problem-solving strategies, you can more effectively select
the right plan of action when faced with challenges in the future. This can help you
solve problems faster and develop stronger critical thinking skills.

15-10-2024

9
Divya K S, Asst Professor,MITS
BENEFITS OF MULTIPLE
PROBLEM-SOLVING STRATEGIES
• 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.

10
15-10-2024
Divya K S, Asst Professor,MITS
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.

This method is used when you don’t have a clear solution in mind and need to
explore different possibilities.

11
15-10-2024
Divya K S, Asst Professor,MITS
STEPS IN THE TRIAL AND ERROR METHOD:
Identify the Problem:
• Clearly understand what you’re trying to solve. Define the problem and your goal.
Try a Possible Solution:
• Start with one approach or solution. This could be based on your intuition, past
experience, or simply a guess.
Test the Solution:
• Implement the solution and observe what happens. Does it solve the problem?
Analyze the Results:
• If the solution works, great! If not, analyze why it didn’t work. What went wrong? What
did you learn from this attempt?
Repeat the Process:
• Based on what you’ve learned, try another solution. Keep experimenting with different
approaches until you find one that works.

12
15-10-2024
Divya K S, Asst Professor,MITS
TRIAL AND ERROR METHOD: EXAMPLE
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.”

13
15-10-2024
Divya K S, Asst Professor,MITS
TRIAL AND ERROR METHOD: WHY IT’S
EFFECTIVE:
Hands-On Learning: Trial and Error is an experiential method, meaning you learn by
doing. Each attempt provides valuable feedback.
Simple and Flexible: It doesn’t require advanced knowledge or techniques, making it
accessible for many types of problems.
Encourages Exploration: Since you’re not locked into one approach, you’re free to
explore multiple avenues until you find what works.

14
15-10-2024
Divya K S, Asst Professor,MITS
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.

15
15-10-2024
Divya K S, Asst Professor,MITS
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 (like systematic
analysis or expert consultation) might be more efficient.

16
15-10-2024
Divya K S, Asst Professor,MITS
ALGORITHMIC
PROBLEM-SOLVING
STRATEGY
An algorithm is a step-by-step, logical procedure that guarantees a solution to a
problem.
It is systematic and follows a defined sequence of operations, ensuring
consistency and accuracy in finding the correct solution.

17
15-10-2024
Divya K S, Asst Professor,MITS
ALGORITHM EXAMPLE:
BAKING A CAKE
1. Gather Ingredients: Measure out 2 cups of flour, 1 cup of sugar, 2 eggs,2 cup of
butter, 1 teaspoon of baking powder, and 1 cup of milk.
2.Preheat Oven: Set the oven to 175°C.
3. Mix Ingredients: In a bowl, combine the flour, baking powder, and sugar. In
another bowl, beat the eggs and then mix in the butter and milk. Gradually
combine the wet and dry ingredients, stirring until smooth.

18
15-10-2024
Divya K S, Asst Professor,MITS
ALGORITHM EXAMPLE:
BAKING A CAKE
4. Prepare Baking Pan: Grease a baking pan with butter or cooking spray.
5. Pour Batter: Pour the batter into the prepared pan.
6. Bake: Place the pan in the preheated oven and bake for 30-35 minutes.
7. Check for Doneness: Insert a toothpick into the center of the cake. If it comes
out clean, the cake is done.
8. Cool and Serve: Let the cake cool before serving.

19
15-10-2024
Divya K S, Asst Professor,MITS
EXAMPLE:
An algorithm is a step-by-step problem-solving strategy based on a formula guaranteed
to give you positive results.
For example, use an algorithm to prepare a tea
Step 1: Put the teabag in a cup.
Step 2: Fill the kettle with water.
Step 3: Boil the water in the kettle.
Step 4: Pour some of the boiled water into the cup.
Step 5: Add milk to the cup.
Step 6: Add sugar to the cup.
Step 7: Stir the tea.
Step 8: Drink the tea.

20
15-10-2024
Divya K S, Asst Professor,MITS
HEURISTIC PROBLEM-SOLVING STRATEGY
A heuristic is a practical approach to problem-solving based on experience and
intuition.
A heuristic is a mental shortcut that allows people to solve problems and make
judgments quickly and efficiently.
It’s a way to simplify complex problems by focusing on the most important factors or
by applying general principles that usually lead to a good enough solution.
It does not guarantee a perfect solution but provides a good enough solution quickly,
often through rules of thumb or educated guesses.

21
15-10-2024
Divya K S, Asst Professor,MITS
HEURISTIC PROBLEM-EXAMPLE
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.

22
15-10-2024
Divya K S, Asst Professor,MITS
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.

23
15-10-2024
Divya K S, Asst Professor,MITS
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.

24
15-10-2024
Divya K S, Asst Professor,MITS
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.

25
15-10-2024
Divya K S, Asst Professor,MITS
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.

26
15-10-2024
Divya K S, Asst Professor,MITS
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.

27
15-10-2024
Divya K S, Asst Professor,MITS
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 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.

28
15-10-2024
Divya K S, Asst Professor,MITS
MEANS-END ANALYSIS: EXAMPLE
Imagine you want to travel from your home to a friend’s house across town.
Goal (End): Arrive at your friend’s house.
Current State: You are at home.
Difference: The distance between your home and your friend’s house.
Action (Means): You decide to drive your car.
Evaluate and Repeat: If there’s traffic on one road, you might choose a different route
(new means) to continue getting closer to your goal.

29
15-10-2024
Divya K S, Asst Professor,MITS
Tower of Hanoi paradigm

30
15-10-2024
Divya K S, Asst Professor,MITS
Tower of Hanoi paradigm
The actual Tower of Hanoi problem consists of three rods sitting vertically
on a base with a number of disks of different sizes that can slide onto any
rod. The puzzle starts with the disks in a neat stack in ascending order of
size on one rod, the smallest at the top making a conical shape. The
objective of the puzzle is to move the entire stack to another rod obeying the
following rules:
1.Only one disk can be moved at a time.
2.Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack or on an empty rod.
3.No larger disc may be placed on top of a smaller disk.

31
15-10-2024
Divya K S, Asst Professor,MITS
Tower of Hanoi paradigm
With 3 disks, the puzzle can be solved in 7 moves. The minimal moves required to solve a
Tower of Hanoi puzzle is 2n – 1, where n is the number of disks. For example, if there were 14
disks in the tower, the minimum amount of moves that could be made to solve the puzzle would
be 214 – 1 = 16,383 moves. There are various ways of approaching the Tower of Hanoi or its
related problems in addition to the approaches listed above including an iterative solution,
recursive solution, non-recursive solution, a binary and Gray-code solutions, and graphical
representations.

32
15-10-2024
Divya K S, Asst Professor,MITS
Tower of Hanoi

33
15-10-2024
Divya K S, Asst Professor,MITS
34
15-10-2024
Divya K S, Asst Professor,MITS
35
15-10-2024
Divya K S, Asst Professor,MITS
36
15-10-2024
Divya K S, Asst Professor,MITS
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.

37
15-10-2024
Divya K S, Asst Professor,MITS
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.

38
15-10-2024
Divya K S, Asst Professor,MITS
BACKTRACKING EXAMPLE:
Sudoku Puzzle:
In a Sudoku puzzle, you fill in numbers in a grid according to specific rules. If
placing a number in a cell violates the Sudoku rules, you backtrack by erasing that
number and trying different numbers until the puzzle is solved.

39
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS
Problem-solving is a systematic way to arrive at solutions for a given
problem.
Understand the problem
This includes understanding the requirements, constraints, and the desired output.
The problem should be broken down into smaller, manageable components.
Formulate a model for the solution
Identify the various ways to solve the problems and formulate a model

40
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS
Develop an algorithm
Once the problem is understood and the model for solution is formulated, the next
step is to design an algorithm—a step-by-step procedure or set of rules to solve the
problem. The algorithm should be efficient, both in terms of time and space
complexity, and should be validated for correctness
Code the algorithm
After designing the algorithm, it is translated into a computer program using a
programming language. The program is composed of instructions that the computer
can execute to perform the desired task. This involves coding, debugging, and
testing.

41
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS
Test the program
The program is tested with different inputs to ensure it behaves as expected. Testing
helps in identifying any errors or inefficiencies in the implementation.
Evaluate the solution
This final step is crucial to ensure that the program effectively addresses the problem
and attains the desired objectives.

42
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING
PROCESS: EXAMPLE
Understand the problem: Here we formally define the problem by
specifying the inputs and output.
Input: The three coefficients a, b and c of the quadratic equation
Output: The discriminant value D for the quadratic equation
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

43
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS: EXAMPLE
Develop an algorithm: A possible algorithm (actually, a pseudocode)
for our discriminant problem is given below:
1 Start
2 Read(a, b, c)
3d=b∗b−4∗a∗c
4 Print(d)
5 Stop

44
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS: EXAMPLE
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)

45
15-10-2024
Divya K S, Asst Professor,MITS
PROBLEM SOLVING PROCESS: EXAMPLE
Test the program: A test suite similar to the one shown in
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.

46
15-10-2024
Divya K S, Asst Professor,MITS
PYTHON PROGRAMMING

Python is a high-level, interpreted language

Python has simple, conventional syntax

Python comes in two flavours: Python 2 and Python 3.

47
15-10-2024
Divya K S, Asst Professor,MITS
HOW TO RUN YOUR PYTHON
CODE?
There are two ways you can run your Python code:
1. using the Python shell
2. running as a standalone script

48
15-10-2024
Divya K S, Asst Professor,MITS
VARIABLES IN PYTHON
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’.
variable is a name that refers to a value
Variable name should be unique in a program

49
15-10-2024
Divya K S, Asst Professor,MITS
VARIABLES IN PYTHON
In Python, we can use an assignment statement to create new variables and
assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Variables must always be assigned values before they are used in the program,
otherwise it will lead to an error.
Wherever a variable name occurs in the program, the interpreter replaces it with
the value of that particular variable.

50
15-10-2024
Divya K S, Asst Professor,MITS
SAMPLE PROGRAM
Write a Python program to find the sum of two numbers.
#To find the sum of two given numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)
#print function in python displays the output
Output:
30

51
15-10-2024
Divya K S, Asst Professor,MITS
SAMPLE PROGRAM
Write a Python program to find the area of a rectangle given that its length is 10
units and breadth is 20 units.
#To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Output:
200

52
15-10-2024
Divya K S, Asst Professor,MITS
RESTRICTION IN VARIABLE
Variable names must start with a letter or the underscore ‘_’ and can be followed by
any number of letters, digits, or underscores.
Variable names are case sensitive; thus, the variable ‘COUNT’ is a different name
from the variable ‘count’.
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.
‘_’ is a valid variable

53
15-10-2024
Divya K S, Asst Professor,MITS
RESERVED WORDS
The following Python code will list all keywords

import keyword
print(keyword.kwlist)

54
15-10-2024
Divya K S, Asst Professor,MITS
DATA TYPE
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.
Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.
Python supports the following data types:
• Number
• String
• List
• Tuple
• Set
• Dictionary

55
15-10-2024
Divya K S, Asst Professor,MITS
DATA TYPES IN PYTHON

56
15-10-2024
Divya K S, Asst Professor,MITS
NUMBERS
The number or numeric data type is used to store numeric values. There are three
distinct numeric types:
The integers include numbers that do not have decimal point. The int data type
supports integers ranging from −231 to 231 − 1.

57
15-10-2024
Divya K S, Asst Professor,MITS
Python uses float type to represent real numbers (with decimal points).
The values of float type range approximately from −10308 to 10308
A floating point number can be written using either ordinary decimal notation or
scientific notation.
Scientific notation is often useful for denoting numbers with very large or very small
magnitudes.

58
15-10-2024
Divya K S, Asst Professor,MITS
complex numbers are written in the form x+yj, where x is the real part and y is the
imaginary part.
int type has a subtype bool. Any variable of type bool can take one of the two
possible boolean values, True and False (internally represented as 1 and 0,
respectively).

59
15-10-2024
Divya K S, Asst Professor,MITS
x=‘abcd'
y=23
z=24.5
l=3993793793793879837937739739770001020
use type(object) to know the type of the variable object

Eg: type(x) type(y) type(z) type(l)


<type 'str'> <type 'int'> <type 'float'> <type 'long'>

60
15-10-2024
Divya K S, Asst Professor,MITS
EXAMPLE
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> Price = -1921.9
>>> type(price)
<class 'float'>

61
15-10-2024
Divya K S, Asst Professor,MITS
SIMPLE DATA TYPE
Variables of simple data types like integer, float, boolean etc. hold single value.
But such variables are not useful to hold multiple data values, for example,
names of the months in a year, names of students in a class, names and numbers
in a phone book.
For this, Python provides sequence data types like Strings, Lists, Tuples, and
mapping data type Dictionaries.

62
15-10-2024
Divya K S, Asst Professor,MITS
SEQUENCE
A Python sequence is an ordered collection of items, where each item is indexed by
an integer value.

Three types of sequence data types available in Python are Strings, Lists and
Tuples.

63
15-10-2024
Divya K S, Asst Professor,MITS
STRINGS
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 (for example ‘Hello’) or in
double quotation marks (for example “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"

64
15-10-2024
Divya K S, Asst Professor,MITS
SLICING IN STRING
str1="foot"
str2="ball"
str1+str2 # concatenation operator
'football‘
Slicing operator - :
Str1[0:2]
Will return “fo”

65
15-10-2024
Divya K S, Asst Professor,MITS
LIST
List is a sequence of items separated by commas and items are enclosed in square
brackets [ ].
Note that items may be of different date types.
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]
Forward indexing and backward indexing
Index starts at 0
For backward indexing index starts at -1

66
15-10-2024
Divya K S, Asst Professor,MITS
ACCESSING ELEMENT OF A LIST
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist)
print(thislist[-4:-1])
['orange', 'kiwi', 'melon']
print(thislist[::-1]) # Reverse a list

67
15-10-2024
Divya K S, Asst Professor,MITS
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 items in the tuple. Similar to List, items may be of different data types.
Example 3.3
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

68
15-10-2024
Divya K S, Asst Professor,MITS
MAPPING

Mapping is an unordered data type in Python.

Currently, there is only one standard mapping data type in Python called
Dictionary

69
15-10-2024
Divya K S, Asst Professor,MITS
DICTIONARY
Dictionary in Python holds data items in key-value pairs and Items 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.
Keys are usually of string type and their values can be of any data type.
In order to access any value in the dictionary, we have to specify its key in square brackets [ ].

Example 3.4
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)']) 120

70
15-10-2024
Divya K S, Asst Professor,MITS
SET
In Python, a set is a collection of unique elements that are unordered and mutable.
Sets are created by placing elements inside curly braces, separated by commas.
For example, three elements could be created:
{1, 2, 3}.
If there are duplicates in the Set, they are automatically removed.

71
15-10-2024
Divya K S, Asst Professor,MITS
NONE KEYWORD
The None keyword is used to define a null value, or no value at all. None is not the
same as 0, False, or an empty string.
Example:
x = None
print(x)
Output: None

72
15-10-2024
Divya K S, Asst Professor,MITS
OPERATORS
An operator is used to perform specific mathematical or logical operation on values.
The values that the operator works on are called operands.
For example, in the expression 10 + num, the value 10, and the variable num are
operands and the + (plus) sign is an operator.
Python supports several kind of operators, their categorization is briefly explained in
this section.

73
15-10-2024
Divya K S, Asst Professor,MITS
OPERATORS
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bit wise Operators
Membership Operators
Identity Operators

74
15-10-2024
Divya K S, Asst Professor,MITS
ARITHMETIC OPERATORS IN PYTHON

75
15-10-2024
Divya K S, Asst Professor,MITS
ARITHMETIC OPERATORS IN PYTHON

76
15-10-2024
Divya K S, Asst Professor,MITS
COMPARISON (RELATIONAL) OPERATORS
• Comparison operators are also called relational operators. The result of a comparison is either True or
False.
• == and != are also known as equality operator
• Comparison operators support chaining. For example, x < y <= z is equivalent to x < y and
y <= z.

77
15-10-2024
Divya K S, Asst Professor,MITS
ASSIGNMENT OPERATORS
The assignment statement creates new variables and gives them values that can be
used in subsequent arithmetic expressions.

78
15-10-2024
Divya K S, Asst Professor,MITS
ASSIGNMENT OPERATORS
You can also assign different values to multiple variables

79
15-10-2024
Divya K S, Asst Professor,MITS
ASSIGNMENT OPERATORS
Python supports the following six additional assignment operators (called compound
assignment operators): +=, -=, *=, /=, //= and %=.

80
15-10-2024
Divya K S, Asst Professor,MITS
LOGICAL OPERATORS
Python includes three Boolean (logical) operators viz. and , or , and not .
The and operator and or operator expect two operands, which are hence called
binary operators.
The and operator returns True if and only if both of its operands are True, and returns
False otherwise.
The or operator returns False if and only if both of its operands are False, and
returns True otherwise.
The not operator expects a single operand and is hence called a unary operator. It
returns the logical negation of the operand, that is, True, if the operand is False, and
False if the operand is True.

81
15-10-2024
Divya K S, Asst Professor,MITS
LOGICAL OPERATORS

In the context of logical


operators, Python interprets all
non-zero values as True and
zero as False.

82
Divya K S, Asst Professor,MITS
15-10-2024
BITWISE OPERATOR
Bitwise operators take the binary representation of the operands and work on their
bits, one bit at a time.
The bits of the operand(s) are compared starting with the rightmost bit- the least
significant bit, then moving towards the left and ending with the leftmost (most
significant) bit.
• 3 types –
1. One’s complement operator
2. Logical bitwise operators
3. Bitwise shift operators

83
15-10-2024
Divya K S, Asst Professor,MITS
ONE’S COMPLEMENT OPERATOR
One’s complement is denoted by the symbol ∼.
It operates by changing all zeroes to ones and ones to zeroes in the binary
representation of the operand.
The operand must be an integer-type quantity.

84
15-10-2024
Divya K S, Asst Professor,MITS
LOGICAL BITWISE OPERATORS
There are three logical bitwise operators:
bitwise and (&),
bitwise exclusive or (∧),
and bitwise or ( | ).
A bitwise and expression will return 1 if both the operand bits are 1. Otherwise, it will
return 0.
A bitwise or expression will return 1 if at least one of the operand bits is 1. Otherwise,
it will return 0.
A bitwise exclusive or expression will return 1 if the bits are not alike (one bit is 0
and the other is 1). Otherwise, it will return 0.

85
15-10-2024
Divya K S, Asst Professor,MITS
LOGICAL BITWISE OPERATORS

86
15-10-2024
Divya K S, Asst Professor,MITS
BITWISE SHIFT OPERATORS

The two bitwise shift operators are shift left (<<) and shift right(>>).

The expression x << n shifts each bit of the binary representation of x to the left, n
times. Each time we shift the bits left, the vacant bit position at the right end is filled
with a zero.

The expression x >> n shifts each bit of the binary representation of x to the right, n
times. Each time we shift the bits right, the vacant bit position at the left end is filled
with a zero

87
15-10-2024
Divya K S, Asst Professor,MITS
BITWISE SHIFT OPERATORS

88
15-10-2024
Divya K S, Asst Professor,MITS
MEMBERSHIP OPERATORS

89
15-10-2024
Divya K S, Asst Professor,MITS
IDENTITY OPERATORS
is and is not are the identity operators in Python.
They are used to check if two values (or variables) are located in the same part of
the memory.
x is y evaluates to true if and only if x and y are the same object.
x is not y yields the inverse truth value.

90
15-10-2024
Divya K S, Asst Professor,MITS
PRECEDENCE AND ASSOCIATIVITY OF
OPERATORS
The order in which operators in an arithmetic expression are applied to their
respective operands is called the precedence of operators. It is also known by other
names, such as priority or hierarchy.
Operators with a higher precedence are applied before operators having a lower
precedence.
If an expression has multiple operators with the same precedence, the tie is resolved
using associativity rules.
Associativity is of two types– Left to Right (L→ R) and Right to Left (R →L).

91
15-10-2024
Divya K S, Asst Professor,MITS
PRECEDENCE RULES IN PYTHON

92
15-10-2024
Divya K S, Asst Professor,MITS
EVALUATION OF AN ARITHMETIC
EXPRESSION

93
15-10-2024
Divya K S, Asst Professor,MITS
PYTHON MODULES

Consider a module to be the same as a code library.


A file containing a set of functions you want to include in your application.
we can use the module by using the import statement:
import <<module_name>>

94
15-10-2024
Divya K S, Asst Professor,MITS
PYTHON MATH
Python has a set of built-in math functions, including an extensive math module, that
allows you to perform mathematical tasks on numbers.
The min() and max() functions can be used to find the lowest or highest value in an
iterable:
• x = min(5, 10, 25)
• y = max(5, 10, 25)
The abs() function returns the absolute (positive) value of the specified number:
• x = abs(-7.25)
The pow(x, y) function returns the value of x to the power of y .
• x = pow(4, 3)

95
15-10-2024
Divya K S, Asst Professor,MITS
THE MATH MODULE
Python has also a built-in module called math, which extends the list of mathematical
functions.
To use it, you must import the math module:
import math
When you have imported the math module, you can start using methods and
constants of the module.
The math.sqrt() method for example, returns the square root of a number:
import math
x = math.sqrt(64)
print(x)

96
15-10-2024
Divya K S, Asst Professor,MITS
THE MATH MODULE
The math.ceil() method rounds a number upwards to its nearest integer, and the
math.floor() method rounds a number downwards to its nearest integer, and returns
the result:

import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1

97
15-10-2024
Divya K S, Asst Professor,MITS
EXAMPLES
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.sqrt(3)
1.7320508075688772

98
15-10-2024
Divya K S, Asst Professor,MITS
INPUT AND OUTPUT IN
PYTHON
input() function for taking values entered by input device such as a keyboard.
The input() function prompts user to enter data.
It accepts all user input (whether alphabets, numbers or special character) as string.
The syntax for input() is:
variable = input([Prompt])
Prompt is the string we may like to display on the screen.
The input() takes exactly what is typed from the keyboard, converts it into a string
and assigns it to the variable on left hand side of the assignment operator (=).

99
15-10-2024
Divya K S, Asst Professor,MITS
EXAMPLE
>>> name = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = int(input("Enter your age: "))
Enter your age: 19
>>> type(age)
<class 'int'>

100
15-10-2024
Divya K S, Asst Professor,MITS
PYTHON OUTPUT
Python uses the print() function to output data to standard output device — the
screen.
The function print() evaluates the expression before displaying it on the screen.
The syntax for print() is:
print(value)

101
15-10-2024
Divya K S, Asst Professor,MITS
EXAMPLE

102
15-10-2024
Divya K S, Asst Professor,MITS
F-STRING (FORMATTED STRING
LITERALS
F-string allows you to format selected parts of a string.

To specify a string as an f-string, simply put an f in front of the string literal, like this:
txt = f"The price is 49 dollars"
print(txt)

To format values in an f-string, add placeholders {}, a placeholder can contain variables,
operations, functions, and modifiers to format the value.
price = 59
txt = f"The price is {price} dollars"
print(txt)

103
15-10-2024
Divya K S, Asst Professor,MITS
CONTENT BEYOND SYLLABUS

104
15-10-2024
Divya K S, Asst Professor,MITS
TYPE CONVERSION
You can convert from one type to another with the int(), float(), and complex()
methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)

105
15-10-2024
Divya K S, Asst Professor,MITS
ESCAPE SEQUENCE
• Python provides special character constants referred to as escape sequences
• An escape sequence refers to a combination of character beginning with a backslash (\) followed by
letters

106
15-10-2024
Divya K S, Asst Professor,MITS
DECIMAL TO BINARY
CONVERSION

107
15-10-2024
Divya K S, Asst Professor,MITS
ERRORS IN PYTHON
PROGRAM
Errors in a Python program are divided into two categories:

1. Syntax errors
2. Semantic errors

108
15-10-2024
Divya K S, Asst Professor,MITS
SYNTAX ERRORS
Programming beginners mostly make typographical errors in their programs.
Such errors are called syntax errors.
Syntax is the set of rules for constructing well-formed expressions or statements
in a language.
A computer generates a syntax error when an expression or sentence is not well
formed.
When Python encounters a syntax error in a program, it halts execution with an
error message indicating the reason for the error. Following are some of the
syntax errors:

109
15-10-2024
Divya K S, Asst Professor,MITS
SYNTAX ERRORS
Name error
Syntax error
Indentation error
Type error

110
15-10-2024
Divya K S, Asst Professor,MITS
NAME ERROR
This error occurs when a referenced variable is not found. See an example:

>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

The error occurs because you try to print the value of the variable x without
assigning any value to it.

111
15-10-2024
Divya K S, Asst Professor,MITS
SYNTAX ERROR
A very common mistake while writing programs is to omit the required
parentheses, as shown below:
>>> print x
File "<stdin>", line 1
print x
^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you
mean print(...)?

112
15-10-2024
Divya K S, Asst Professor,MITS
INDENTATION ERROR
Indentation is very significant in Python code.
Each line of code must begin in the leftmost column, with no leading spaces.
The only exception to this rule occurs in control statements and definitions, where nested
statements must be indented one or more spaces.
An indentation error is raised when there is an incorrect indentation. See below:
>>> print(x)
File "<stdin>", line 1
print(x)
IndentationError: unexpected indent
Note the extra space between the prompt >>> and print(x).

113
15-10-2024
Divya K S, Asst Professor,MITS
TYPE ERROR
Python is a strongly typed programming language. This means that the interpreter
checks the data types of all operands before performing any operation.
If the type of an operand is not appropriate, the interpreter halts execution with an
error message.
This error checking prevents a program from attempting to do something that it
cannot do. See an example:
>>> 5+'3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

114
15-10-2024
Divya K S, Asst Professor,MITS
SEMANTIC ERRORS
Semantics is the set of rules that allows the computer to interpret the meaning of
expressions or statements.
A semantic error is detected when the action that an expression describes cannot
be carried out, even though that expression is syntactically correct.
Division by zero is the most common semantic error.
>>> 7/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

115
15-10-2024
Divya K S, Asst Professor,MITS
116
15-10-2024
Divya K S, Asst Professor,MITS

You might also like