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

Module 1 Algorithmic Thinking With Python

The document outlines a course on algorithmic thinking using Python, covering problem-solving strategies, the problem-solving process, and essential programming concepts. It details various approaches to problem-solving, including trial and error, heuristics, means-ends analysis, and backtracking, along with their applications and limitations. Additionally, it emphasizes the importance of understanding algorithms, pseudocode, and flowcharts in programming, as well as the steps involved in writing and testing code.

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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views123 pages

Module 1 Algorithmic Thinking With Python

The document outlines a course on algorithmic thinking using Python, covering problem-solving strategies, the problem-solving process, and essential programming concepts. It details various approaches to problem-solving, including trial and error, heuristics, means-ends analysis, and backtracking, along with their applications and limitations. Additionally, it emphasizes the importance of understanding algorithms, pseudocode, and flowcharts in programming, as well as the steps involved in writing and testing code.

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 PDF, TXT or read online on Scribd
You are on page 1/ 123

ALGORITHMIC THINKING

WITH PYTHON
Module 1
Module 1
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.


Module 2
ALGORITHM AND PSEUDOCODE REPRESENTATION:- Meaning and Definition
of Pseudocode, Reasons for using pseudocode, The main constructs of
pseudocode - Sequencing, selection (if-else structure, case structure) and
repetition (for, while, repeat-until loops), Sample problems

FLOWCHARTS :- Symbols used in creating a Flowchart - start and end, arithmetic


calculations, input/output operation, decision (selection), module name (call), for
loop (Hexagon), flow-lines, on-page connector, off-page connector.
Module 3
SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range,
while loop. Sequence data types in Python - list, tuple, set, strings, dictionary,
Creating and using Arrays in Python (using Numpy library).

DECOMPOSITION AND MODULARIZATION :- Problem decomposition as a


strategy for solving complex problems, Modularization, Motivation for
modularization, Defining and using functions in Python, Functions with multiple
return values.

RECURSION:- Recursion Defined, Reasons for using Recursion, The Call Stack,
Recursion and the Stack, Avoiding Circularity in Recursion,
Module 4
COMPUTATIONAL APPROACHES TO PROBLEM-SOLVING:-

Brute-force Approach, Divide-and-conquer Approach, Dynamic Programming


Approach, Greedy Algorithm Approach, Randomized Approach
Module 1
Course outcome 1: Utilize computing as a model for solving
real-world problems.
Problem-solving

1. Identify the problem


2. Determining the
causes of the problem
3. Deciding the best
course of action
4. Implementing the
action to solve the
problem

Effective problem-solving requires you to identify the problem, select the right
process to approach it and follow a plan tailored to the specific issue you are trying
to solve.
Example of Problem
1. Solving a math problem, like 𝑥+2=5
The goal (find x), the constraints (use basic arithmetic), and the solution (x=3)
are all clear and unambiguous.

2. Designing a marketing campaign to improve a company’s brand image.


3. Assembling a bookshelf using the provided parts and instruction
4. Sort the list of numbers 3,7,8,4,2
5. Where should I go for the next vacation
6. Design a new product that people will love
Types Problem-solving
Two types of Problem solving

● Well defined problem


● ill defined problem
Well-Defined Problem
1. Goal is clear
2. Constraints are known
3. Specific path to the solution

Ill Defined problem


1. Goal is unclear
2. Constraints are not well specified
3. Multiple or unclear solutions
Problem Solving Strategies
Effective problem solving involves in selecting and applying the appropriate
strategies to identify,analyse and resolve problems
.

3.
Problem Solving Strategies
● Different problems are required to be approached in different ways to find the
best solution.
● Learning various problem-solving strategies allows for the selection of the
right plan of action when faced with challenges in the future.
● This helps to solve problems faster and develop stronger critical thinking
skills.
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.
● Using trial and error, different solutions are attempted sequentially until the
problem is solved.
● Although trial and error is not typically the most time-efficient strategy, it is a
commonly used one.

This approach can be a good option

● Do not have a clear idea to solve the problem


● Problem isn't too complex or costly if you make mistake
● if there are a limited number of possibilities to consider
Example

● Broken printer, Restarting phone, turning off WiFi, turning off bluetooth in
order to determine why your phone is malfunctioning
● Finding a recipe, learning to ride a bike, swimming
● Solving puzzles
● In programming - change a part of the code, test the program and check if the
issue is resolved
● Machine learning training to recognize a pattern - different models are tested

Limitation
● Can be slow and waste of time( more possibilities or complex)
● Does Not provide a structured method to solve the problem
Heuristic
● Sometimes, it’s more effective to solve a problem based on a formula than to
● try different solutions blindly.
● Mental shortcuts that are used to solve problems. A “rule of thumb” is an
example of a heuristic.
● Such a rule saves the person time and energy when making a decision
● Despite its time-saving characteristics, it is not always the best method for
making a rational decision.

Limitation
● Lead to mistake if the rules arent accurate
Example

● Navigation systems, heuristics help by suggesting the most


promising routes to take, so you don't waste time exploring every
possible path.
● Searching online
● Decision making
● Route planning
● Medical diagnosis
● Game playing
Means ends analysis
● Involves in identifying the current state and the desired goal state, then finding
a way to reduce the difference between the two.
● This usually involves breaking down the problem into smaller, manageable
sub-goals (or sub-problems) and solving these incrementally.
● This strategy involves choosing and analyzing an action at a series of smaller
steps to move closer to the goal.
Steps involved in Means-Ends Analysis
1. Setting up the goal
2. Understanding the current state
3. Identifying the steps
4. Breaking down the problem
5. Step by step progress
Example
● Tower of Hanoi paradigm involves choosing and analyzing an action at a series of
smaller steps to move closer to the goal
● Planning a trip
● career goal setting
● writing an essay
● project management
● software development
1. Setting up the goal
● Deciding what is the end goal.
● The goal is to move all three disks from the first peg to the third peg
2. Understanding the current state
● Looking at the current situation
● The current state involves all three disks stacked on the first peg in order of size, with
the largest disk at the bottom and the smallest at the top
3. Identifying the Steps

● Figure out what actions or steps need to be taken to bridge the gap between the
starting point and your goal
● Moving disks between pegs while adhering to the rules
4. Breaking Down the Problem
The problem is broken down into sub goals and each of these sub goals brings closer
towards the final goal.

● Goal: Move all 3 disks from Peg A to Peg C.


○ Sub-goal 1: Move the top 2 disks from Peg A to Peg B.
○ Sub-goal 2: Move the largest disk (Disk 3) from Peg A to Peg C.
○ Sub-goal 3: Move the 2 disks from Peg B to Peg C.
Sub Goal 1 Sub Goal 2

Sub Goal 3
5. Step-by-Step Progress
By tackling each of these smaller tasks one at a time,we steadily move closer towards the
final goal.

● This approach can be effective if


■ Goals are clear

● Limitation
■ Complex Problem lt can be tricky when the problem is very complex or when it's hard to break
down into smaller parts.
Backtracking
● Backtracking explore different options to find the best solution.
● They work by trying out different paths and if one doesn’t work, they backtrack and
try another until they find the right one
● It is commonly used in situations where you need to explore multiple possibilities to
solve a problem, like searching for a path in a maze or solving puzzles like Sudoku.
● When a dead end is reached, the algorithm backtracks to the previous decision point
and explores a different path until a solution is found or all possibilities have been
exhausted.
Backtracking algorithm
1. Choose an initial solution.
2. Explore all possible extensions of the current solution.
3. If an extension leads to a solution, return that solution.
4. If an extension does not lead to a solution, backtrack to the previous solution and try a
different extension.
5. Repeat steps 2-4 until all possible solutions have been explored.
Example
Input: A maze

Algorithm:

1. Start at the starting point.


2. For each of the four possible directions (up, down, left, right), try moving in that direction.
3. If moving in that direction leads to the ending point, Proceed
4. If moving in that direction does not lead to the ending point, backtrack to the previous
position and try a different direction.
5. Repeat steps 2-4 until the ending point is reached or all possible paths have been explored.
This approach can be effective if

● There are multiple possible solutions to the problem.


● The problem can be broken down into smaller subproblems.
● The subproblems can be solved independently.
● Backtracking is very thorough because it ensures all possible options are explored.
This means you won't miss the right solution.

Limitation

Time-Consuming: This method can be slow, especially if there are many possible options
to check. It might take a lot of time to find the right solution.
Example
● Solving a Sudoku puzzle: If you place a number incorrectly, you backtrack and try a
different number.
● Solving mazes: If you hit a dead end in a maze, you backtrack to a previous choice
point and choose a different path.
● Crossword puzzles: When a word doesn’t fit, you backtrack and choose different
letters.
● Finding a file in a directory: If searching in one folder doesn't work, you backtrack
and explore other directories.
● Chess problem solving: If a move leads to a losing position, you backtrack and
choose a different move.
● Finding the shortest path through a maze
● Scheduling problems
Tutorial 1
1. Use a diagram to solve the Tower of Hanoi for three pegs with the minimum
number of moves.
2. Evaluate different algorithms discussed earlier based on their efficiency by
counting the number of steps.
Computer as a model of computation
● Computer science focuses on solving problems using computers

● The problems to be solved can come from real-world scenarios or abstract concepts
Computer’s information processing model

● Problems are solved on a computer by


receiving user input
● Processing that input
● Producing output (such as images, text, or
sound)
● In some cases, the input and output data
may involve hard drives or network
devices.
Example
Calculate the average grade for all students in a class.

1. Input: get all the grades


2. Process: add them all up and compute the average grade.
3. Output: output the answer to either the monitor, to the printer, to the USB flash drive
or hard disk or a combination of any of these devices.
Problem Solving Process
Problem Solving is the sequential process of analysing information related to a given
situation and generating appropriate response options.

Problem solving process

1. Understanding the Problem


2. Formulating a Model
3. Developing an Algorithm
4. Writing the Program
5. Testing the Program
6. Evaluating the Solution
1. Understanding the problem
The problem context, objectives and constraints need to be understood.

Several techniques are used to gather information about the problem

● Conducting Interviews
● Sending questionnaires to stakeholders
● Segmenting the problem into small sub problem
Grades?
1. What input data or information is available?
2. What does the data represent?
3. In what format is the data provided?
4. What is missing from the available data?
5. Is all the necessary information available to solve the problem?
6. What output information needs to be produced?
7. In what format should the result be presented: text, image, or graph?
8. What additional requirements are necessary for computation?
2. Formulating a Model
1. Should identify the various way to solve the problem
a. Brainstorming - generate large number of ideas in short span of time
2. The ideas are transformed into models
3. Model should accurately reflect the conceived idea
4. Key goal- determining how to effectively use the available data to compute a
solution.

Average1 = (x1 + x2 + x3 + ⋯ + xn)/n if x is a whole number


● A+ = 12, A = 11, A− = 10, B+ = 9, B = 8, B− = 7, C+ = 6, C = 5, C− = 4, D+ = 3, D = 2, D− = 1,
F=0

Average2 = (y1 + y2 + y3 + ⋯ + yn)/n

The output

Expressed as a percentage, either Average1 can be used directly, or ([Average2/12]*100)

Expressed as letter grade (Average1/100 ∗ 12) or (Average1 ∗ 0.12) or Average2


Developing an Algorithm

Algorithm is a precise sequence of instructions for solving a problem.

Two commonly used representations for an algorithm are:

1. Pseudocode: pseudocode is a simple and concise sequence of English-like


instructions to solve a problem.
2. Flowcharts: A visual representation of the problem-solving process.
Example Pseudocode
Simple Interest

1. Start

2. Read(principal, rate, years)

3. SI = (principal ∗ rate ∗ years)/100

4. Print(SI)

5. Stop.
Flowchart
Pseudocode and Algorithm
Pseudocode is often used as a way of describing a computer program to someone who
doesn’t understand how to program a computer.

Flowcharts can be visually appealing but pseudocode is often the preferred choice for
algorithm development because:

● Flowcharts can be difficult to draw neatly, especially when errors occur.


● Pseudocode is easier to fit on a single page.
● It can closely resemble real programming code, making it easier to later translate into
a program.
● Writing pseudocode is faster than drawing flowcharts.
● Pseudocode can vary based on the individual who writes it.
● It is essential for the algorithm to be clearly articulated without ambiguity regarding
the order of the steps.
● An algorithm should be tested by manually going through the steps in mind to make
sure a step or a special situation is not missed out.
Writing the Program
● Writing a program is often referred to as "coding" or "implementing an algorithm”.
● The code (or source code) represents the actual program.
● Structure of the code mirrors the algorithm, it may appear less readable and more
mathematical.
Pseudocode Program
1. Start p = 1000
2. Read(principal, rate, years) r = 10
3. SI = (principal ∗ rate ∗ years)/100 n = 2
simple_interest = (p * n * r) / 100
4. Print(SI)
print(simple_interest)
5. Stop.
Interpreter
● Definition 1-2-3: Interpreting converts the high-level language program into machine
code. An interpreter reads the source code line-by-line, converts it into
machine-understandable form, executes the line, and then proceeds to the next line.
● This is unlike a compiler that takes the entire source code and converts it to object
code.
● The interpreter first reads a Python expression or a statement and verifies that it is
valid with regard to the rules, or syntax, of the language. Any invalid statement is
called a syntax error. When the interpreter encounters such an error, it halts with an
error message.
● Example incorrect indentation or syntax mistakes, missing colons (:) after control
statements (like if, for, while) will cause the program to fail.
Test the program
● Next step is to inspect the code to verify its correctness. This is called testing.
● During testing, the program is evaluated as to whether it produces the desired output.
● Any unexpected output is an error.
● The program should be executed with different sets of inputs to detect errors.
● It is impossible to test the program with all possible inputs.
● Instead, a smaller set of representative inputs called test suite is identified and if the
program runs correctly on the test suite, then it is concluded that the program will
probably be correct for all inputs.
Test Suite
Bug and Debug
● Bugs are errors with a program that cause it to stop working or produce incorrect or
undesirable results.
● It is the responsibility of the programmer to fix as many bugs in a program as present. To
find bugs effectively, a program should be tested with many test cases (called a test suite).
● Debugging is the process of finding and fixing errors in program code.
● Debugging is often a very time-consuming “chore” when it comes to being a
programmer. Involves fixing or resolving the errors (technically called bugs) identified
during testing. Testing and debugging should be repeated until all errors are fixed
Evaluating the Solution
● This final step is crucial to ensure that the program effectively addresses the
problem and attains the desired objectives.
● The evaluation criteria could be metrics like correctness, performance,
efficiency, feasibility, and scalability.
● The potential risks that could arise with the program’s deployment are also to
be assessed.
● If the solution meets the requirement and perform well then it can be
considered complete
● If there are areas for improvement, the algorithm need to be redefined or
program need to be optimized
Creating and using variables in Python
Character
The set of characters supported by a programming language is called character
set. A character can be an alphabet, a digit, or a special symbol. Python supports
the following characters:
● upper case alphabets (A–Z)
● lower case alphabets (a–z)
● digits (0–9)
● special symbols like @,#,%,$ etc.
Python maps each valid character to an integer value called ASCII value 'A' is 65
Constant
● A ‘constant’ is an entity whose value doesn’t change.
Variables
● A variable is a name that refers to a value.
● To simplify the retrieval and use of data values, these memory locations are
given names.

age = 25
name = "John" Multiple Assignment
is_student = True x, y, z = 5, 10, 15
student_name = "Alice" Constants
number_of_books = 10
average_grade = 89.5 PI = 3.14159
car_model_2022 = "Tesla" MAX_STUDENTS = 30
days_in_week = 7
Rules (Must Follow)
Start with a letter or an underscore (_):

A variable name must begin with either a letter (a-z, A-Z) or an underscore ( _ ),
but not with a number.

● Valid: age, _name, var_1


● Invalid: 1age, 9name

Use letters, numbers, and underscores:

After the first character, you can use letters, numbers, or underscores.

● Valid: student_name, number_of_days_3


● Invalid: student-name, number@3
Case-sensitive:

Variable names are case-sensitive, meaning myVar and myvar are different.

● Valid: age and Age are two separate variables.

Cannot be a Python keyword:

You cannot use Python keywords (like if, for, while, etc.) as variable names. These
are reserved words in Python.

● Invalid: if, for, class


Keywords
● A keyword in Python is a reserved word that has a predefined meaning and
function within the language.
● Keywords are part of the Python syntax, and they cannot be used as variable
names, function names, or any other identifiers.
● All the keywords except True, False, and None are in lowercase, and they
must be written as is.
● Python has 29 keywords
29 Keywords
Data Types
● A data type in Python defines the kind of value a variable can hold and the
operations that can be performed on that value.
● Different data types in Python categorize data into specific types, such as
numbers, text, or more complex structures.

Key Characteristics:

● Defines the nature of the data: What type of data is being stored (e.g.,
text, number, list).
● Determines operations: Each data type supports specific operations (e.g.,
you can add numbers, but not strings and numbers directly).
● Python is dynamically typed: Python automatically detects the type based
on the assigned value.
Numbers
The number or numeric data type is used to store numeric values. There are three
distinct numeric types

● integer
● float
● complex
1. Integer
The integers include numbers that do not have decimal point. The int datatype
supports integers ranging from −231 to 231 − 1.

Example: 10, - 42
2. Float
● represent real numbers (with decimal points). float type supports from −10308
to 10308 and have 16 digits of precision (number of digits after the decimal
point).
● 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.
● Example: 3.14, -0.001

Decimal notation Scientific notation Meaning

3.146 3.146e0 3.146 × 100

314.6 3.146e2 3.146 × 102

0.3146 3.146e-1 3.146 × 10−1


3. Complex
● complex numbers are written in the form x+yj, where x is the real part and y is
the imaginary part.
Example : 3+5j, 10j

4. Boolean
● 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).
Example: is_student = True
String
● A string literal or a string is a sequence of characters enclosed in a pair of
single quotes or double quotes.
● Multi-line strings are written within a pair of triple quotes, ``` or """.
● The strings ' ' and " " are called empty strings.

Key Characteristics of Strings:

● Immutable: Once a string is created, it cannot be changed (although you can


create new strings based on it).
● Ordered: Strings can be indexed, meaning each character in the string has a
position (starting from 0).
Example
● greeting = "Hello, World!"
● name = 'Alice'
● multiline = '''This is a multiline string which can have multiple lines of content
line string.'''
● Immutable example
String Operations:
1. Concatenation: Combine strings using the + operator.
2. Repetition: Repeat a string multiple times using the * operator.
3. String Length: Use len() to find the length of a string.
4. Accessing Characters: Access individual characters using indexing.
5. Slicing: Extract a substring using slicing.

string[start:end:step]
Function
● A function is a named block of statements that carries out some specific,
well-defined task.
● Functions are of two types: built-in and user-defined functions.
● Built-in functions are those that are provided by the interpreter itself. These
include I/O functions, mathematical functions,etc.
● User-defined functions are those that are created by the programmers.
● A function can take input values called parameters or arguments to process
and give back an output value, which is known as return value.
Using the math module

The math module in Python provides access to many mathematical functions and
constants. It allows you to perform various mathematical operations like finding the
square root, computing the factorial, trigonometric functions, logarithms, etc. To
use a function or a constant of the math module, you need to do two things:

1. import the module

import math

2. Access the function or the constant by prefixing its name with ”math.”

(math followed by a dot)


1. Mathematical Constants

1. math.pi: Returns the value of π (pi), approximately 3.14159.


2. math.e: Returns the value of Euler’s number e, approximately 2.71828.
2. Basic Functions
1. math.sqrt(x): Returns the square root of x.
2. math.pow(x, y): Returns x raised to the power y (i.e., x**y).
3. math.factorial(x): Returns the factorial of x (only for non-negative
integers).
4. math.floor(x): Returns the largest integer less than or equal to x (rounds
down).
5. math.ceil(x): Returns the smallest integer greater than or equal to x
(rounds up).
6. math.fabs(x): Returns the absolute value of x as a float.
7. math.gcd(x, y): Returns the greatest common divisor of x and y.
3. Trigonometric Functions
1. math.sin(x): Returns the sine of x (where x is in radians).
2. math.cos(x): Returns the cosine of x (where x is in radians).
3. math.tan(x): Returns the tangent of x (where x is in radians).
4. math.degrees(x): Converts x from radians to degrees.
5. math.radians(x): Converts x from degrees to radians.
4. Logarithmic and Exponential Functions
1. math.log(x): Returns the natural logarithm of x (base e).
2. math.log(x, base): Returns the logarithm of x with the specified base.
3. math.log10(x): Returns the base-10 logarithm of x.
4. math.exp(x): Returns e raised to the power of x (i.e., e**x).
5. Hyperbolic Functions:
1. math.sinh(x): Returns the hyperbolic sine of x.
2. math.cosh(x): Returns the hyperbolic cosine of x.
3. math.tanh(x): Returns the hyperbolic tangent of x.
Handling basic I/O - print, input

1. Data input refers to collecting or retrieving data from external sources (like
the user or a file)
2. Data output refers to sending or saving data to external sources (like
displaying information on the screen or writing to a file).
input() method
● To receive input from the user, which accepts the input as a string.
● Since input() returns the input as a string, you often need to convert it to
other data types (e.g., integer, float).
Output - print()
Python uses the method print. It just prints whatever is given inside
the quotes.
String Concatenation
Using f-strings
Escape Sequence
● An escape sequence refers to a combination of characters beginning with a
backslash (\) followed by letters.

Escape Sequence Meaning

● \b - Backspace
● \n - Newline
● \t - Horizontal tab
● \v - Vertical tab
● \\ - The \ character
● \' - Single quotation mark
● \" -Double quotation mark
Class test
1. Explain any two problem-solving strategies
2. To input the side of a square and find its area
Operators in python

Operators are symbols that perform operations on the values or


variable(operands)
● OPERATORS: These are the special symbols. Eg- + , * , /, etc.
● OPERAND: It is the value on which the operator is applied.

Example

add= num1+num2
Types of operators
● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators
1. Arithmetic operator
● Arithmetic operators help perform mathematical operations such
as addition, subtraction, multiplication, and division.
Example
a = 10

b=3

print(a + b) # Outputs: 13

print(a / b) # Outputs: 3.3333


The precedence of Arithmetic Operators in Python is as follows:
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the same precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same precedence)
6. S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For
example:
● x % 10 -> yields the last digit
● x % 100 -> yield last two digits
2. Comparison(Relational) Operators
● Comparison operators are used to compare two values and return a boolean
result (True or False). a=10 b=5
Example
a = 10

b=5

print(a == b) # Outputs: False

print(a > b) # Outputs: True


● = is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

● In Python, the comparison operators have lower precedence than the


arithmetic operators. All the operators within comparison operators have the
same precedence order.
Assignment operator
● Assignment operators allow you to assign values to variables while
performing operations.
● The basic assignment is done with =, but there are several others that
combine assignment and arithmetic operations.

Syntax: variable name = values

Example: num1=10
Compound assignment operators
● Compound assignment operators are +=, -=, *=, /=, //=, %=
● They are equivalent to below expressions
Example
x=5

x += 3

print(x) # Outputs: 8
Logical operator
● Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations.
● It is used to combine conditional statements. These are often used with
boolean values (True or False).
Example
a = True

b = False

print(a and b) # Outputs: False

print(a or b) # Outputs: True

print(not a) # Outputs: False


Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:


1. logical not
2. logical and
3. logical or
Bitwise Operators
Bitwise operators work on the binary representation of numbers. They are mainly
used for operations at the bit level.

a=6 b=2

| a|b
Logical bitwise operators
● 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.
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.
Example

a=6 # Binary: 110

b=2 # Binary: 010

print(a & b) # Outputs: 2 (Binary: 010)


Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:


1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
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.
Example
a = 10

b = 20

c = 10

print(a is not b) #True

print(a is c) #True
Membership Operators

These operators test for the membership of a data item in a sequence, such as a
string.

Two membership operators are used in Python.

● in– Evaluates to True if it finds the item in the specified sequence and False
otherwise.
● not in– Evaluates to True if it does not find the item in the specified sequence
and False otherwise.
Example

● 'A' in 'ASCII' # Output: True


● 'a' in 'ASCII' #output: False
● 'a' not in 'ASCII' #output: True
String Manipulation

1. Concatenation
2. Repetition
3. Find the length of the string
4. Slicing
5. String reversal

You might also like