0% found this document useful (0 votes)
11 views127 pages

Module - I

python

Uploaded by

vidhyapm
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)
11 views127 pages

Module - I

python

Uploaded by

vidhyapm
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/ 127

Module – I

UCEST105 - ALGORITHMIC THINKING WITH PYTHON

Compiled By
Mr. Shyam Krishna K
Assistant Professor
Dept. of AI & DS
Muthoot Institute of Technology & Science
shyamkrishnak@mgits.ac.in
Syllabus (7 Hours)

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.

UCEST105 | Module - I 2
Course Outcome -
“Interpret problem-solving strategies by using computing as a
model for addressing near real-world problems.”

UCEST105 | Module - I 3
PROBLEM-SOLVING
STRATEGIES

UCEST105 | Module - I 4
PROBLEM SOLVING
• Definition: Problem solving is the process of transforming the
description of a problem into the solution by using our knowledge
and by relying on our ability to select and use appropriate problem-
solving strategies and tools to implement.

UCEST105 | Module - I 5
Phases of problem solving process
• 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?

UCEST105 | Module - I 6
Phases of problem solving process
• 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.

UCEST105 | Module - I 7
Phases of problem solving process
• 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?

UCEST105 | Module - I 8
Phases of problem solving process
• 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?

UCEST105 | Module - I 9
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, and Backtracking, each
offering unique benefits and applications.
• 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.

UCEST105 | Module - I 10
Importance of Problem-solving strategies
1. Problem solving strategies encompass various approaches and
methods used to address challenges effectively, facilitating
decision making and innovation.
2. Different fields, from science to business, benefit immensely
from understanding diverse problem-solving strategies and
improved outcomes.
3. Learning and Applying various strategies fosters cognitive
development, enhancing critical thinking and analytical
capabilities.

UCEST105 | Module - I 11
Importance of Problem-solving strategies
4. Understanding multiple strategies promotes cognitive flexibility,
allowing individuals to adapt diverse challenges in various
contexts.
5. Knowledge of various strategies equips individuals to evaluate
and select the most effective approaches for a given problem.
6. From healthcare to engineering, utilizing diverse strategies
enables practical solutions tailored to specific problems.

UCEST105 | Module - I 12
Benefits of understanding various 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.
• 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

UCEST105 | Module - I 13
Well-defined Problems
• A well-defined problem is one where the initial state, goal state,
and the methods to reach the goal state are clearly defined.
• A well defined problem is also called as a formal problem.
• Features of well-defined problems:
• They have clear goal state
• They have a given starting situation i.e. mental state
• They have a set of resources or operators to control.
• They have ownership or mental representations
• Examples:
• The game of chess
• The Hanoi Tower Problem

UCEST105 | Module - I 14
Ill-defined problem
• An ill-defined problem, lacks clear specification of the initial state,
the goal state, or the methods for achieving the goal.
• Ill defined problems are not well defined.
• They don't have any clear goals, solution paths or expected
solution.
• Examples:
• Designing a Sustainable City
• Writing a Novel
• Resolving Workplace Conflict

Understanding the nature of the problem helps in choosing the


right approach to solving it

UCEST105 | Module - I 15
Difference between Well-defined problems and Ill-defined problems.

Well-defined Problems Ill-defined Problems


Clear goals and Objectives Unclear and Vague goals and Objectives
Specific, measurable outcomes Multiple , conflicting outcomes
Well defined constraints Ambiguous or uncertain constraints
Relevant data available Insufficient data available
Single , Identifiable Solution Multiple possible solutions
Logical, step by step approach Requires creative, iterative approach
Ex : Chess Game, Tower of Hanoi, N- Ex: Paint a beautiful picture, Designing
Queens Problem etc. a Sustainable City, Writing a Novel,
Resolving Workplace Conflict etc.

UCEST105 | Module - I 16
Methods to study problem solving
1. Introspection:
• Involves individuals reflecting on and reporting their own thought
processes as they solve problems.
• Participants are asked to “think aloud” or describe their mental steps.
• While useful for gaining insights into cognitive strategies, introspection
can be subjective and may not capture unconscious processes.
2. Simulation:
• Involves creating artificial scenarios that mimic real-world problem-
solving situations.
• Researchers can control variables and observe how people approach and
solve problems in these simulated environments.
• This allows for more standardized conditions than real-world
observations.

UCEST105 | Module - I 17
Methods to study problem solving
3. Computer Modelling:
• It involves creating computational models that attempt to replicate
human problem-solving processes.
• These models can be based on cognitive theories and tested against
human performance data.
• It allows for rapid testing of hypotheses and can reveal potential
mechanisms underlying problem-solving behaviours.
4. Experimentation:
• Involves designing controlled studies to test specific hypotheses about
problem-solving processes.
• Researchers manipulate variables and measure outcomes to understand
how different factors affect problem-solving performance.
• Experiments can be conducted in laboratory settings or in more
naturalistic environments.

UCEST105 | Module - I 18
Strategies for Problem Solving
• An individual uses various kinds of methods or strategies to solve
problems.
• Some strategies when used take a long time but definitely give an
answer.
• On the other hand, there are some other strategies which take lesser
time but do not always guarantee success.
• 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.

UCEST105 | Module - I 19
Strategies for Problem Solving
• These strategies can be mainly classified
1. Trial and error - Continue trying different solutions until problem is
solved
2. Algorithm - Step-by-step problem-solving formula
3. Heuristic - General problem-solving framework
4. Means-end analysis
5. Backtracking - Working backward

UCEST105 | Module - I 20
Trial and Error
• Involves repeated attempts to solve a problem, where each failure
leads to insights that guide subsequent actions until a solution
emerges.
• For example, 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.

UCEST105 | Module - I 21
Trial and Error
• Advantages and Disadvantages: This method is often
straightforward and can yield solutions without complex planning;
however , it may lead to inefficiencies and waste resources if the
approach is not methodical.
• This method is practical when there is no clear pathway to the
solution and allows for discovering the correct answer through
persistence and adaptability.

UCEST105 | Module - I 22
Algorithm
• It is a defined series of steps designed to solve a specific problem,
characterized by precision, repeatability, and efficiency in
execution.
• Steps involved in algorithmic thinking: Key steps include
problem definition, data gathering, establishing parameters, step by
step instruction, creation and analysis of outcomes to refine the
approach.
• Algorithms are used frequently in our everyday life.
• Algorithms are used by Google, Facebook, and so on.

UCEST105 | Module - I 23
Heuristic Approach

• Heuristics are mental shortcuts or rules of thumbs that simplify the


decision making process, enabling individuals to draw conclusions
and solve the problems more rapidly.
• Different types of heuristics are used in different types of
situations, but the impulse to use a heuristic occurs when one of
five conditions is met
• When one is faced with too much information
• When the time to make a decision is limited
• When the decision to be made is unimportant
• When there is access to very little information to use in making the
decision
• When an appropriate heuristic happens to come to mind in the same
moment

UCEST105 | Module - I 24
Backtracking
• Backtracking or Working backwards is a useful heuristic in which
you begin solving the problem by focusing on the end result.
• It gradually finds a set of all possible solutions using a recursive
call. Because a problem will have constraints, solutions that do not
meet them will be removed.
• It finds a solution by building a solution step by step, increasing
levels over time, A search tree known as the state-space tree is used
to find these solutions.
• Each branch in a state-space tree represents a variable, and each
level represents a solution.

UCEST105 | Module - I 25
Backtracking
• The algorithm determines whether the proposed solution satisfies
the constraints. If it does, it will keep looking. If it does not, the
branch is removed, and the algorithm returns to the previous level.

Search Space Tree

UCEST105 | Module - I 26
Means-End Analysis
• Means-end analysis is a goal oriented problem-solving technique
that focuses on breaking down a problem into smaller, manageable
sub-goals to reach the overall objective.
• The process includes identifying your goal, assessing the current
situation, determining the means to progress and systematically
implementing those means to bridge the gap.
• Means-ends analysis (MEA) is an effective problem-solving
approach that involves dividing a problem into smaller goals and
identifying the means that stand in the way of the current state and
the desired goal.

UCEST105 | Module - I 27
Means-End Analysis
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.

UCEST105 | Module - I 28
Tower of Hanoi paradigm

UCEST105 | Module - I 29
• 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.

UCEST105 | Module - I 30
Summary of Problem-Solving Strategies
Method Description Example
Trial and Continue trying different solutions until Restarting phone, turning off
error problem is solved WiFi, turning off Bluetooth in
order to determine why your
phone is malfunctioning
Algorithm Step-by-step problem solving formula Instruction manual for installing
new software on your computer
Heuristic General problem-solving framework rule of thumb
Means-ends Analysing a problem at series of smaller Envisioning the ultimate goal
analysis steps to move closer to the goal and determining the best strategy
for attaining it in the current
situation
Backtracking Working backwards is a useful heuristic in N-Queens Problem
which you begin solving the problem by
focusing on the end result

UCEST105 | Module - I 31
THE PROBLEM SOLVING
PROCESS

UCEST105 | Module - I 32
THE 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

UCEST105 | Module - I 33
THE PROBLEM SOLVING PROCESS

• The problems that we want to


solve can come from any real-
world problem or perhaps even
from the abstract world. We
need to have a standard
systematic approach to solving
problems.
• Since we will be using
computers to solve problems, it
is important to first understand
the computer’s information
processing model.

UCEST105 | Module - I 34
Computer as a model of computation
• In solving a problem, there are some well-defined steps to be
followed. For example, consider how the input/process/output
works on a simple problem:
• Example: Calculate the average grade for all students in a class.
• Input: get all the grades … possibly by typing them in via the keyboard
or by reading them from a USB flash drive or hard disk.
• Process: add them all up and compute the average grade.
• 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.

UCEST105 | Module - I 35
Understand the Problem
• The first step to solving any problem is to make sure that one
understands the problem about to be solved. One needs to know:
• What input data/information is available?
• What does the data/information represent?
• In what format is the data/information?
• What is missing in the data provided?
• Does the person solving the problem have everything needed?
• What output information needs to be produced?
• In what format should the result be: text, picture, graph?
• What are the other requirements needed for computation?

Example: Understand the problem -


“Calculate the average grade for all students in a class.”

UCEST105 | Module - I 36
Formulating a Model
• The next step is to understand the processing part of the problem.
• Many problems break down into smaller problems that require
some kind of simple mathematical computations in order to
process the data.
• 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.

Formulate a model for the problem -


“Calculate the average grade for all students in a class.”

UCEST105 | Module - I 37
Develop an Algorithm

• Having understood the problem and formulated a model, it is time


to come up with a precise plan of what the computer is expected to
do.
• 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
1. Pseudo code, or
2. Flowcharts.

UCEST105 | Module - I 38
Pseudocode & Flowchart | Ex – Broken Lamp

Pseudocode Flowchart
1. IF lamp works, go to step 7.
2. Check if lamp is plugged in.
3. IF not plugged in, plug in lamp.
4. Check if bulb is burnt out.
5. IF blub is burnt, replace bulb.
6. IF lamp doesn’t work buy new lamp.
7. Quit ... problem is solved.

UCEST105 | Module - I 39
Develop an Algorithm

• Whether using a flow chart of pseudocode, an algorithm should be


tested by manually going through the steps in mentally to make
sure a step or a special situation is not missed out.
• Often, a flaw will be found in one’s algorithm because a special
situation that could arise was missed out.
• Only when one is convinced that the algorithm will solve the
problem, should the next step be attempted.

Give an algorithm for the problem -


“Calculate the average grade for all students in a class.”

UCEST105 | Module - I 40
Writing the Program
• The next step is to transform the algorithm from step 3 into a set of
instructions that can be understood by the computer.
• Writing a program is often called "coding" or “implementing an
algorithm”. So the code (or source code) is actually the program
itself.
• the source code would vary depending on the programming
language that was used. (C, C++, Python, Java etc.)

UCEST105 | Module - I 41
Test the Program
• Once a program is written and compiles, the next task is to make
sure that it solves the problem that it was intended to solve and that
the solutions are correct.
• Running a program is the process of telling the computer to
evaluate the compiled instructions.
• It is possible however, that a program works correctly for some set
of input data but not for all.
• If the output of a program is incorrect, it is possible that the
algorithm was not properly converted into a proper program.
• It is also possible that the programmer did not produce a proper
algorithm back in step 3 that handles all situations that could arise.

UCEST105 | Module - I 42
Test the Program
• Bugs are errors with a program that cause it to stop working or
produce incorrect or undesirable results.
• 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.

UCEST105 | Module - I 43
Evaluating the Solution
• Once the program produces a result that seems correct, the original
problem needs to be reconsidered to make sure that the answer is
formatted into a proper solution to the problem.
• There may be a need to display the information in a way that helps
visualize or interpret the results with respect to the problem;
perhaps a chart or graph is needed.

UCEST105 | Module - I 44
ESSENTIALS OF PYTHON
PROGRAMMING

UCEST105 | Module - I 45
What is Python?
• Python is a popular programming language. It was created by
Guido van Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting

UCEST105 | Module - I 46
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and
modify files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.

UCEST105 | Module - I 47
Why Python?
• Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can
be very quick.
• Python can be treated in a procedural way, an object-oriented way
or a functional way.

UCEST105 | Module - I 48
Python Syntax compared to other programming languages

• Python was designed for readability, and has some similarities to


the English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or
parentheses.
• Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this purpose.

UCEST105 | Module - I 49
The Python interpreter

50
Character set
• The set of characters supported by a programming language is
called character set.
• A character can be an alphabet, a digit, or a special symbol.
• Python supports the following characters:
• upper case alphabets (A–Z)
• lower case alphabets (a–z)
• digits (0–9)
• special symbols like @,#,%,$ etc.

51
Constants, variables, and keywords
• A ‘constant’ is an entity whose value doesn’t change. 3, 100, etc.
are all constants.
• The data on which programs operate are stored in various memory
locations. These memory locations are given names. Since the
value stored in each location may change occasionally, the names
given to these locations are called ‘variable names’ or simply
‘variables’.
• Thus, a variable is a name that refers to a value.

52
Constants, variables, and keywords
• 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.

53
Constants, variables, and keywords
• Keywords(also called reserved words) are special words, reserved
for other purposes; thus, they cannot be used as variable names.
• Python has thirty-three keywords
• All the keywords except True, False, and None are in lowercase,
and they must be written as is.

54
Data types
• Any data item stored in memory has an associated data type.
• The data type of an item defines the operations that can be
performed on it, and how the values are stored in memory.
• Python supports the following data types:
• Number
• String
• List
• Tuple
• Set
• Dictionary

55
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

56
Numbers
• Python uses float type to represent real numbers (with decimal
points).
• The values of float type range approximately from −10308 to 10308
and have 16 digits of precision.
• A floating point number can be written using either ordinary
decimal notation or scientific notation.

57
Numbers
• 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).

58
Strings
• A string literal or a string is a sequence of characters enclosed in
a pair of single quotes or double quotes.
• "Hi", "8.5", `hello' are all strings.
• Multi-line strings are written within a pair of triple quotes, ``` or
""".

59
Statements
• A statement is an instruction that the Python interpreter can
execute.
• A statement can be an expression statement or a control statement.
• An expression statement contains an arithmetic expression that the
interpreter evaluates.
• A control statement is used to represent advanced features of a
language like decision-making and looping

60
Python expressions
• An arithmetic expression comprises operands and operators.
• Operands represent data items on which various operations are
performed.
• The operations are denoted by operators.
• The operands can be constants or variables.
• When a variable name appears in the place of an operand, it is
replaced with its value before the operation is performed.
• The operands acted upon by arithmetic operators, must represent
numeric values.
• Thus, the operands can be integer quantities, floating-point
quantities, or even characters

61
Operators in Python
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

62
Arithmetic Operators

The floor division operator (//)


returns the floor value of the
quotient of a division operation.

63
Assignment operator

• ‘=’ is the assignment operator.


• The assignment statement creates new
variables and gives them values that can be
used in subsequent arithmetic expressions.

• Python allows you to assign a single value to


several variables simultaneously.

64
Assignment operator

• You can also assign different values to multiple variables

65
Assignment operator

• Python supports the following six additional assignment


operators (called com pound assignment operators): +=,-=,
*=, /=, //= and %=.

66
Comparison Operators
• Comparison operators are also called relational operators.
• The result of a comparison is either True or False.
• == and != are also known as equality operators.

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

68
Logical Operators

• Truth Tables:

• In the context of logical operators,


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

69
Bitwise operators
• 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

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

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

72
Logical bitwise operators

73
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

74
Bitwise shift operators

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

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

77
Precedence and associativity of operators
• The order in which operators in an arithmetic ex pression 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 oper ators 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).

78
Precedence rules in Python
Precedence group Operators Associativity
Parenthesis () L →R
Exponentiation ** R →L
Unary plus, Unary minus, One’s complement +,-, ∼ R →L

Multiplication, Division, Floor division, *, /, //, % L →R


Modulus
Addition, Subtraction +, - L →R
Bitwise shift operators <<, >> L →R
Bitwise AND & L →R
Bitwise XOR ^ L →R
Bitwise OR | L →R
Comparisons, Identity and Membership ==, !=, <=, >=, > is, is not, L →R
operators in, not in
Logical NOT not R →L
Logical AND and L →R
Logical OR or L →R
Assignment operators =, +=,-=, *= /=, //=, %= R →L
79
Python Modules

UCEST105 | Module - I 80
What is a Module?
• 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>>

UCEST105 | Module - I 81
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)
UCEST105 | Module - I 82
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)

UCEST105 | Module - I 83
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

UCEST105 | Module - I 84
The Math Module
• The math.pi constant, returns the value of PI (3.14...):
import math

x = math.pi

print(x)

UCEST105 | Module - I 85
Function Description

ceil(x) Returns the smallest integer greater than or equal to x.

fabs(x) Returns the absolute value of x

factorial(x) Returns the factorial of x

floor(x) Returns the largest integer less than or equal to x

isnan(x) Returns True if x is a NaN

pow(x, y) Returns x raised to the power y

sqrt(x) Returns the square root of x

cos(x) Returns the cosine of x

hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)

sin(x) Returns the sine of x

tan(x) Returns the tangent of x

degrees(x) Converts angle x from radians to degrees

radians(x) Converts angle x from degrees to radians

exp(x) Returns e**x


UCEST105 | Module - I 86
trunc(x) Returns the truncated integer value of x
Input and Output

UCEST105 | Module - I 87
Input
• When a program asks for user input, it should first print a message
that tells the user which input is expected. Such a message is called
a prompt.
• In Python, displaying a prompt and reading the keyboard input is
combined in one operation.
first = input("Enter your first name: ")
• The input function displays the string argument in the console
window and places the cursor on the same line, immediately
following the string.
Enter your first name: ❚
• The user enters data using the keyboard, and the return key ends
the input.
Here, in this example, the variable “first” is assigned with the
input given by user

UCEST105 | Module - I 88
Input – Ex:
name = input("Enter your name : ")
city = input("Enter your city : ")
print("Hello My name is", name)
print ("I am from ", city)

w = input("Enter width : ")


width = int(w)
h = input("Enter height : ")
height = int(h)

width = int(input("Enter width : "))


height = int(input("Enter height : "))
area = width*height
print ("Area of rectangle = ", area)
UCEST105 | Module - I 89
Output
• Python's print() function is a built-in function. It is the most
frequently used function, that displays value of Python expression
given in parenthesis
print("Hello, World!")

• F-Strings (Formatted String literals)


• F-string allows you to format selected parts of a string.

UCEST105 | Module - I 90
F-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)

UCEST105 | Module - I 91
Additional Contents

UCEST105 | Module - I 92
Python Quickstart
• Python is an interpreted programming language, this means that as
a developer you write Python (.py) files in a text editor and then
put those files into the python interpreter to be executed.

• The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py

UCEST105 | Module - I 93
Hello World Program

print("Hello, World!")

UCEST105 | Module - I 94
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Creating a Comment
• Comments starts with a #, and Python will ignore them:
• Ex:
#This is a comment
print("Hello, World!")

UCEST105 | Module - I 95
Python Comments
• Comments can be placed at the end of a line, and Python will
ignore the rest of the line:
• Ex:
print("Hello, World!") #This is a comment

• A comment does not have to be text that explains the code, it can
also be used to prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")

UCEST105 | Module - I 96
Multiline Comments
• Python does not really have a syntax for multiline comments.
• To add a multiline comment you could insert a # for each line:
• Ex:
#This is a comment
#written in
#more than just one line
print("Hello, World!")

UCEST105 | Module - I 97
Multiline Comments
• Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code,
and place your comment inside it:
• Ex:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

UCEST105 | Module - I 98
Python Variables
• Variables are containers for storing data values.
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Ex:
x = 5
y = "John"
print(x)
print(y)

UCEST105 | Module - I 99
Python Variables
• Variables do not need to be declared with any particular type, and
can even change type after they have been set.
• Ex:
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

UCEST105 | Module - I 100


Casting
• If you want to specify the data type of a variable, this can be done
with casting.
• Ex:
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

UCEST105 | Module - I 101


Get the Type
• You can get the data type of a variable with the type() function.
• Ex:
x = 5
y = "John"
print(type(x))
print(type(y))

UCEST105 | Module - I 102


Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:
• Ex:
x = "John"
# is the same as
x = 'John'

UCEST105 | Module - I 103


Case-Sensitive
• Variable names are case-sensitive.
• Ex:
a = 4
A = "Sally"
#A will not overwrite a

UCEST105 | Module - I 104


Variable Names
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
• Rules for Python variables:
1. A variable name must start with a letter or the underscore character
2. A variable name cannot start with a number
3. A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three
different variables)
5. A variable name cannot be any of the Python keywords.

UCEST105 | Module - I 105


Variable Names

• Ex: • Ex:
Legal Variable Names Illegal Variable Names
myvar = "John" 2myvar = "John"
my_var = "John" my-var = "John"
_my_var = "John" my var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

UCEST105 | Module - I 106


Multi Words Variable Names
• Variable names with more than one word can be difficult to read.
• There are several techniques you can use to make them more
readable
1. Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
2. Pascal Case
Each word starts with a capital letter: MyVariableName = "John"
3. Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

UCEST105 | Module - I 107


Many Values to Multiple Variables
• Python allows you to assign values to multiple variables in one
line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

UCEST105 | Module - I 108


One Value to Multiple Variables
• And you can assign the same value to multiple variables in one
line:
x = y = z = "Orange"
print(x)
print(y)
print(z)

UCEST105 | Module - I 109


Unpack a Collection
• If you have a collection of values in a list, tuple etc. Python allows
you to extract the values into variables. This is called unpacking.
• Ex:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

UCEST105 | Module - I 110


Python Data Types

UCEST105 | Module - I 111


Python Data Types
Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can
do different things.
• Python has the following data types built-in by default, in these
categories:
Text Type: str
Numeric Types: int, float, complex
Boolean Type: bool
etc.

UCEST105 | Module - I 112


Python Data Types
• You can get the data type of any object by using the type()
function:
• Ex:
x = 5
print(type(x))
<class 'int'>

UCEST105 | Module - I 113


Setting the Specific Data Type
• If you want to specify the data type, you can use the following
constructor functions:

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = bool(5) bool

UCEST105 | Module - I 114


Python Numbers
• There are three numeric types in Python:
1. int
2. float
3. complex
• Variables of numeric types are created when you assign a value to
them:
x = 1 # int
y = 2.8 # float
z = 1j # complex

UCEST105 | Module - I 115


Int
• Int, or integer, is a whole number, positive or negative, without
decimals, of unlimited length.
x = 1
y = 35656222554887711
z = -3255522

UCEST105 | Module - I 116


Float
• Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
• Float can also be scientific numbers with an "e" to indicate the
power of 10.
x = 35e3
y = 12E4
z = -87.7e100

UCEST105 | Module - I 117


Complex
• Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j

UCEST105 | Module - I 118


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)

UCEST105 | Module - I 119


Python Strings
• Strings in python are surrounded by either single quotation marks,
or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print() function:
print("Hello")
print('Hello’)
• You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

UCEST105 | Module - I 120


String Concatenation

• To concatenate, or combine, two strings you can use the +


operator.
a = "Hello"
b = "World"
c = a + b
print(c)
• To add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)

UCEST105 | Module - I 121


Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to
return a part of the string.

b = "Hello, World!" Get the characters from position


print(b[2:5]) 2 to position 5 (not included)

Slice From the Start


• By leaving out the start index, the range will start at the first
character:
b = "Hello, World!" Get the characters from the start
to position 5 (not included)
print(b[:5])

UCEST105 | Module - I 122


Slice to the end
• By leaving out the end index, the range will go to the end:
b = "Hello, World!" Get the characters from position
print(b[2:]) 2, and all the way to the end

Upper Case
• The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
• The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
UCEST105 | Module - I 123
String Methods
Method Description
capitalize() Converts the first character to upper case
count() Returns the number of times a specified value occurs in a string
islower() Returns True if all characters in the string are lower case
isdigit() Returns True if all characters in the string are digits
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
replace() Returns a string where a specified value is replaced with a
specified value
title() Converts the first character of each word to upper case
upper() Converts a string into upper case

UCEST105 | Module - I 124


Escape sequences
• Python provides special character constants referred to as escape
sequences
• An escape sequence refers to a combination of characters
beginning with a backslash (\) followed by letters

UCEST105 | Module - I 125


UCEST105 | Module - I 126
Thank You…
Compiled By,
Shyam Krishna K
Asst. Professor
Dept. of AI & DS
Muthoot Institute of Technology & Science

UCEST105 | Module - I 127

You might also like