Python Computational Problem Solving Notes
Python Computational Problem Solving Notes
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #2
Problem Solving – Computational and Non-Computational
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Introduction
A king has three wives and four children. Three of the children are Ram, Lakshman, and
Bharat. Compute the name of the fourth child. We do not expect a computational process
to answer this problem – instead it would be a guess, not a computation.
Next, let us consider the other problem. Consider a ball at rest, high up somewhere. We
wish to compute the distance the ball will travel, when released from rest, over the period
starting at the 4th second and ending at the 7th second. We can use the laws of motions to
compute this number given a Computing device. This is our notion of computation.
Computing:
The process of utilizing computer technology to complete a task. Computing may
involve computer hardware and/or software but must involve some form of a computer
system. It is purely a physical phenomenon occurring inside a closed system called a
computer. It includes designing, developing, and building hardware and software systems;
processing, structuring, and managing various kinds of information; doing scientific research
on and with computers; making computer systems behave intelligently; and creating and
using communications and entertainment media.
Problem Solving:
Problem: Task/job to be completed
The task or job can be either Computational or Non-Computational.
▪ Computational: Problem that can be solved by a computer
▪ Non-Computational: Problem that cannot be solved by a
computer
Essence of CPS
The Man, Cabbage, Goat and Wolf problem is a River Crossing problem.
A man lives on the east side of a river. He wishes to bring a cabbage, a goat, and awolf to
a village on the west side of the river to sell.
However, his boat is big enough to hold himself and either the cabbage, goat, or wolf. In
addition, the man cannot leave the goat alone with the cabbage because the goat will eat
the cabbage, and he cannot leave the wolf alone with the goat because the wolf will eat
the goat. How does the man solve his problem?
Solution:
There is a simple algorithmic approach for solving this problem by simply trying all
possible combinations of items that may be rowed back and forth across the river.
Trying all possible solutions is referred to as a brute force approach.
Representation:
There are 4 symbols – M(Man), C(Cabbage), G(Goat) and W[Wolf].
There are totally 24 States = 16 states
Assume all the items are the East(E) side of the river and they need to reach the
West(W) side by following the constraints involved in the problem.
Choose the valid states from the below list of states of each symbol.
[E, E, E, E], [E, E, E, W], [E, E, W, E], [E, E, W, W], [E, W, E, E], [E, W, E, W], [E, W, W, E],
[E, W, W, W], [W, E, E, E],
[W, E, E, W], [W, E, W, E], [W, E, W, W], [W, W, E, E], [W, W, E, W], [W, W, W, E], [W,
W, W, W]
Algorithm:
Algorithm
Solution 1 Solution 2
Step 1: Start Step 1: Start
Step 2: Man rows goat Step 2: Man rows goat
Step 3: Man rows back alone Step 3: Man rows back alone
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #3
Limits of Computation Problem Solving, Algorithms
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Algorithm:
A sequence of unambiguous instructions for solving a problem, i.e., for obtaining a
required output for any legitimate input in a finite amount of time. The word “algorithm”
is derived from the ninth-century Arab mathematician, Al-Khwarizmi.
Characteristics of an Algorithm:
Definiteness, Finiteness, Effectiveness, Correctness
Types of Algorithms:
• Deterministic:
Algorithm which always produce the same output with a particular input with
the underlying machine always passing through the same sequence of states.
Example: Sorting Algorithms
• Non-deterministic:
Provide different outputs for same input on different executions. Example:
Execution of concurrent algorithms with race condition.
Example: Write an algorithm to find the sum of the digits of a given number n.
Step 1: Start
Step 2: Read the number, n
Step 3: Declare sum as 0
Step 4: Remainder =n modulus 10 (or n remainder 10)
sum = sum + Remainder
n = n / 10
Step 5: if n>0 go to step 4 else go to step 6
Step 6: print the sum
Step 7: Stop
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #4
Digital Computer – Computer Hardware
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Computer:
An electronic device that stores, retrieves, and processes data and can be
programmed with instructions. A programmable device designed for performing prescribed
operations on data and has links to other devices for receiving the inputs, storing,
processing, retrieving it for later use and displaying the data. Computers are available in
variety of sizes and configurations.
Types of Computers
• Digital computers
• Analog computers
• Quantum computers
• DNA computers
• Molecular Computers
• Micro-fluidics based computer
• Servers
• Specialized computers - Smart phones, Wearables, Game consoles, TVs
The Digital computer is the most used type of computer and is used to process
information with quantities using digits, usually using the binary number
system.
Number System
It is defined as the representation of numbers by using digits or other symbols in a
consistent manner. The value of any digit in number can be determined by a digit, its
position in the number, and the base of the number system.
Processing devices:
Central Processing Unit (CPU) - The “brain” of a computer system. Interprets and
executes instructions.
Graphics Processing Unit (GPU)
Main Memory:
Memory or space where currently executing programs reside. It is volatile. Means
the contents are lost when the power is turned off.
Secondary Memory:
It provides long-term storage of programs and data. Non-volatile, the contents are
retained when power is turned off. Can be magnetic (hard drive), optical (CD or DVD), or
flash memory (USB drive).
Input devices:
“Way to tell computer what to do”
You can try to name a few of them from the below picture.
Output devices:
“How computer shows you what it is doing”
Try naming a few of them from the picture.
Communication devices:
A hardware device capable of transmitting an analog or digital signal over the
telephone, other communication wire, or wirelessly.
Buses:
A communication system that transfers data between components inside a computer,
or between computer and output devices.
- Internal Bus (System Bus: CPU and Main Memory)
- External Bus (Expansion Bus: printer to the computer)
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #5
Digital Computer – Computer Software: Operating System
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Software Components:
Computer software is a set of program instructions, including related data and
documentation, that can be executed by computer. The software component is the set of
instructions that makes the computer work. Held either on your computer’s hard disk, CD-
ROM or DVD. Loaded (i.e. copied) from the disk into the computer’s RAM (Random Access
Memory), as and when required.
The first computer programs ever written were for a mechanical computer designed by
Charles Babbage (The Father of Computer) in the mid-1800s. Ada Lovelace was the person
who wrote these programs. she is referred to as “the first computer programmer.”
Differences between System Software and Application Software are listed below.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #6
Syntax, Semantics and Program Translation
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Syntax:
The syntax of a language is a set of characters allowed in the language in a specific
order or sequence(arrangement). Basically, it is the set of rules to be followed in a particular
language.
Example: English includes the letters of the alphabet, punctuation, and properly spelled
words and properly punctuated sentences. Syntax in English sets forth a specific order for
grammatical elements like subjects, verbs, direct and indirect objects, etc.
The following is a syntactically correct sentence in English,
“Hello there, how are you?”
The following, however, is not syntactically correct,
“Hello there, how are you”
“Hello there, hoe are you?”
Semantics:
The semantics of a language is the meaning associated with each syntactically
correct sequence of characters.
Example:
“how you hello are?”
This sentence is syntactically correct but has no meaning. Thus, it is semantically incorrect.
The above discussion on syntax and semantics is general discussion. We will be discussing
about the python syntax and semantics later.
Note: Every language has its own syntax and semantics.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #9
Process of Computational Problem Solving and Translation Models
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Problem Analysis:
In this phase, it is must to understand the fundamental computational issues involved.
Good to know what constitutes a solution. For some problems, there is only one solution.
For others, there may be a number (or infinite number) of solutions. Thus, a problem may
be stated as finding,
• A solution
• An approximate solution
• A best solution
• All solutions
Design:
Divide the problem into smaller sub-problems or tasks. Identify the main components
or steps needed to solve the problem. Create a high-level plan or algorithm for solving each
sub-problem. Choose appropriate data structure.
Implementation:
Involves putting the project plan into action. Decision regarding the paradigms of the
programming language is finalized in this phase.
Testing:
The focus is on investigation and discovery. During the testing phase, the team finds
out whether their code is working according to customer requirements. Error is the state
or condition of being wrong in conduct or judgement. Errors are always pervasive,
persistent and inevitable.
Pervasive: Error can spread over if there is error in the beginning itself
Persistent: Errors are continuous in any application
Inevitable: Unavoidable
Translation Models:
Translation models describe the mathematical relationship between two or more
languages. A translator is a programming language processor that converts a computer
program from one language to another. It can translate a high-level language program into
a machine language program that the central processing unit (CPU) can understand. There
are many Translators. Let us deal with Compiler and Interpreter in detail.
Compiler: Converts entire high-level language programs to machine language at once
Note: Python has Hybrid model of Interpreter and Compiler. We will discuss few
examples on this as and when we cover different constructs in python.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #10
Programming Paradigms and Introduction to Python
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
How does a computer understand a program in a middle level or high level language?
We require a mechanism to translate a program written in a middle level or high-level
language to a program in a machine language. These are called translators. Different
translators are discussed in Lecture #9.
How many Programming Languages are there? And Which one to choose?
Many / Infinity …
Choose the right language based on the application
TIOBE Index:
The TIOBE Programming Community index is an indicator of the popularity of
programming languages. The index is updated once a month. The ratings are based on the
number of skilled engineers world-wide, courses and third-party vendors. There are 25
search engines that are used to calculate the TIOBE index. Popular search engines such as
Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube, and Baidu etc. It is important to note
that the TIOBE index is not about the best programming language or the language in
which most lines of code have been written.
Why Python?
Life is all about selecting between the alternates. You must have debated before
selecting Engineering over medicine, selecting college A over college B. I am sure you
would have some criteria before choosing between the alternates – Your parents run a
hospital, your uncle is a software specialist, your neighbors whom you do not like boast a
lot about their child’s achievement or you tossed a coin to decide.
It is equally same here too. We have umpteen number of languages to choose from.
After lots of experiments with various languages, we have decided that you should start
your journey in programming with Python. Recently Stanford also changed over to Python
as the first language to be taught.
We prefer Python for a number of reasons. The most important reasons are:
• Simple to learn
• Easy to master
• Extensively used in the industry
• Extensively used in research
Features of Python:
• Uses an elegant syntax, making the programs you write easier to read.
• Is an easy-to-use language that makes it simple to get your program working.
• Comes with a large standard library that supports many common programming tasks
such as connecting to web servers, searching text with regular expressions, reading
and modifying files. Python Package index contains a more than 72000 packages. It
includes GUIs, test frameworks, automation and web scraping, scientific computing,
text processing, image processing, graph generation
• Python's interactive mode makes it easy to test short snippets of code. There's also
a bundled development environment called IDLE.
• Runs anywhere, including Mac OS X, Windows, Linux and Unix.
• Is free software in two senses. It doesn't cost anything to download or use Python,
or to include it in your application. Python can also be freely modified and re-
distributed, because while the language is copyrighted it's available under an open-
source license.
• A variety of data structures(types) are available: numbers (floating point, complex,
and unlimited length long integers), strings (both ASCII and Unicode), lists, and
dictionaries.
• The language supports object-oriented programming with classes and multiple
inheritance. Also supports raising and catching exceptions, resulting in cleaner error
handling.
• Code can be grouped into modules and packages.
• Contains advanced programming features such as generators and list
comprehensions.
• Automatic memory management feature of python frees you from having to
manually allocate and free memory in your code.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #11
First Program in Python, Program Structures and Running a
Program
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
• Ubuntu: Install Python on Ubuntu/Linux | install python through terminal | easy steps
- YouTube
Note: Few of the Operating systems have Python installed by default. You can upgrade it to
a specific version.
Interactive mode: The computer will keep displaying the results immediately.
- Open the Terminal (Ctrl+Alt+T) or Command Prompt. Type python3 or py or py -3 or
python
- You should be getting the below default python prompt (>>>).
- How to come out of python prompt? Type exit() or quit() and then press enter key.
You will be out of python prompt and OS Prompt is back to you now.
Batch mode: We should explicitly indicate that we want to display something using a special
command. You can view the created file anytime later.
- Create a file containing the commands/statements in python.
Program Structure:
- In the beginning of the program, all statements should start from the first column
(column 0)
- Executes as it exists – top to bottom
- Case sensitive constructs are used in the language
- A statement must be in one line. If it must span multiple lines,
Escape the new line using \
Use a construct which has begin and end markers
To have more than one statement on a single line, separate using ;
- Format of code is rigid – Not a free format
Examples:
1. The below code results in Indentation Error
2. Output of below code is first Hello world and in the next line it is python
More examples will be dealt once we start with output function in detail.
Refer to Lecture #12.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #12
Output function
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Observation: Runs one statement at a time. Here, we need not tell the interpreter what to
be displayed because of the statement execution. When you press the enter key, the result
is displayed without any extra instruction like print. It does the same job when you use the
print function in interpreter mode.
Batch mode
Observation: No output from the first four lines of code. Output of next three lines are there
in the output window. Here, we need to explicitly tell the interpreter what should be
displayed as a result of the program. Python has a specialized function that does just that,
called the print function.
Note: In Batch mode, we must use the function print for displaying information to the
output screen
Function: A group of commands that performs a specified task. It may take some input, do
some processing, and returns a result(output). In programming, input given to a function
are called arguments. For more details, refer to Lecture #51
Print in detail :
Print is a function that takes input and as part of the processing, displays the value of
the argument to the output screen. We will be calling this print function using a call operator
(). Let us get the help page of print to understand it better.
Few Examples:
Example 1: Can take any type of arguments
In all above examples, we see that if there is more than one argument to print, they are
separated by a space and between two print calls, there is a new line in the output. This is
because of the keyword parameters sep and end respectively. The default value for sep is
space (‘ ‘) and the default value for end is ‘\n’ (newline).
Example 5:
Now think about printing only 2 digits after the decimal point in each expression like
5/7. Possible using the format function in python. The built-in format function can
be used to produce a numeric value containing a specific number of decimal places.
More about this will be discussed in Lecture #17.
Example 6:
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #13
Variables, Data types and id
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Identifiers:
A sequence of one or more characters used to provide a name for a given program
element. Python is case sensitive. Example: Line is different from line. Few rules to be
followed are here:
• Identifiers may contain letters and digits but cannot begin with a digit.
• The underscore character (_) is also allowed to aid in the readability of long identifier
names. However, it should not be the first character, as identifiers beginning with an
underscore have special meaning in Python.
Keywords:
An identifier that has predefined meaning in a programming language. Therefore,
keywords cannot be used as “regular” identifiers. Doing so will result in a syntax error.
How do you list the set of keywords in python?
Note: Press q to come out of help page and then enter exit() / quit()
Variables:
A variable is a name (identifier) that is associated with a value. A variable is created
the moment you first assign a value to it. It can be assigned different values during a
program execution. Hence the name variable.
Note: Every variable in Python is a reference (a pointer) to an object and not the actual
value itself. For example, the assignment statement just adds a new reference to the right-
hand side.
Program 1:
a = 10
k = 10
print(a)
print(k)
Output: 10
10
Program 2:
a = 10
k =a
print(a)
print(k)
Above diagram and output remains the same.
Point to think: If you change the value of k, will the value of a be changed? – Nooo!
Observation: In 1 and 2, Variables a and k are both associated with the same literal value
10 in memory. One way to prove this is by the use of built-in function id().
id() : Id function produces a unique number identifying a specific value (object) in memory.
Program 5: usage of variable sep and end along with the keyword parameter for print
Literals:
In arithmetic, we talk about values which do not change. Even in programming, we
talk about entities which do not change. They are considered as they are. They are said to
be constants or literals. A literal is a sequence of one or more characters that stands for itself.
Literals can be categorized into: Numeric literals and String Literals
Numeric Literals:
• A literal containing only the digits 0–9, an optional sign character (+ or -), and a
possible decimal point.
• If a numeric literal contains a decimal point, then it denotes a floating-point value ,
or “ float ” (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10).
• Commas are never used in numeric literal.
• Complex numbers have a real and imaginary part.
• There is no limit to the size of an integer that can be represented in Python
Data Types:
Every variable is associated with a type based on the value assigned to it.
Significance of data types are listed below.
• Range of values allowed in a variable.
• Memory allocation for a variable
• Allowed set of operations on the data
type() in python: A built in function, which returns the type of the given object.
Reference types:
Structured or reference types having more than one value.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #14
Input function
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Input() in Python
This function is used to read a string from the user. It returns a value as a string, which
must be stored in a variable for future use.
Input function can be used to display the message to the user using the prompt
field and then displays the cursor to the user to take some input from the user.
Program 1:
Write a program to read length and breadth of a rectangle and find the perimeter
of it.
Solution Version - 1:
length = input()
breadth = input()
print(length+breadth+length+breadth)
The above code just did the concatenation of two strings entered by the user. Few
problems with the code are as follows:
• Type conversions not done for any string entered by the user.
• User doesn’t get any prompt message to enter the number.
Now, we will add all these program elements in version 2 solution.
If the user input is known, then we can use int(), float(), complex() etc. to convert
the entered string to specific type. But if the user input is unknown, which function
helps me in this conversion?
The eval() is a built-in- function used in python which parses the string and
evaluates the string like a python expression. Think about the output of
print(eval(“2+4-1”)).
Note: If user-supplied input is directly passed into eval(), it can lead to code
injection vulnerabilities. Better to avoid the usage of this function.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Operator and Operand: A symbol that denotes the operation to be performed on the
data in the process of computational problem solving is known as an operator. The data
used with operators is said to be operands.
Categories of Operators:
o Based on the number of operands, the operator takes
Unary, Binary, Ternary
o Based on the operation
Arithmetic, Logical, Relational, Membership, Identity, Bitwise,
Assignment, Shorthand etc.
Arity / Rank: Refers to the number of operands required for the operator.
o Unary – 1 operand
Example expressions: +5, -2, ~a, not 5, (-a)
o Binary - 2 operands
Example expressions: 7+5, 1-2, a^b, a>b, a>10 or b<20, (s//3)
o Ternary - 3 operands [Will be discussed later]
if else
Note:
# is the Single line comment. Comments are ignored by the compiler/interpreter.
‘’’ and ‘’’ or “”” and “”” are used as multiline comments. They are multiline strings in
actual.
Cascading operations
print(3 > 2 > 1) #Same as 3>2 and 2> 1
print(10 == 10 == 10) #Same as 10 == 10 and 10 == 10
print(3>2<1) #False
Think about how these operators work with other collections like Lists, strings etc. ?
• False Values:
False. 0 , ‘’ (Empty String), [] , {} , () (Empty Collections)
• True Values:
True, non – Zero numbers, Non Empty String, Non Empty Collections
These operators perform short circuit evaluation or lazy evaluation -Evaluate
a logical expression left to right and stop the evaluation as soon as the truth
or the falsehood is found.
Logical and: If the first operand evaluates to false, then regardless of the
value of the second operand, the expression is false
Logical or: If the first operand evaluates to true, regardless of the value of
the second operand, the expression is true.
Note: Python interpreter does not evaluate the second operand when the
result is known by the first operand alone
>>> 2 and 5 >>> 0.0 or "pes"
5 'pes'
>>> 0 and 5 >>> "pes" or ""
0 'pes'
>>> 3 and 0.0 >>> 5.2 or 5
0.0 5.2
>>> 3 and "pes" >>> not 0
'pes' True
>>> 3 and "" >>> not 1.3
'' False
>>> not 1
>>> a=3
False
>>> b=-4
>>> not "pes"
>>> a>b and b<4
False
True
>>> not ""
>>> a>b and b>4
True
False
>>> not 0.000
>>> a>b or b>a
True
True
>>> a =1
>>> "" and 0.0
>>> a and True
''
True
>>> 3 or 5
>>> 0 and True
3
0
>>> 3 or 0
>>> True and 0
3
0
>>> 0 or 7
>>> 0 or True
7
True
Bitwise Operators: &, |, ^, >>, <<, ~
These operators operate on the binary value of the given operand. They operate on
a bit-level, which means that each binary digit is considered.
>>> a = 6
>>> b = 6
>>> a is b
True
>>> a is not b
False
>>> id(a) is id(b) #DO not worry much about the output as the id function works
differently in interpreter mode and batch mode. Kindly do not break your head!!! Just to
wake you up, this expression has been added.
False
Assignment Operator: =
It assigns the value of the right side expression to a left side variable. Using = in an
expression doesn’t evaluate to a value. Hence this is considered as a statement in python
rather than an expression.
>>> a = 5 >>> print(a = 3)
>>> a Traceback (most recent call last):
5 File "<stdin>", line 1, in <module>
>>> a = 6//3 TypeError: 'a' is an invalid keyword argument
>>> a for print()
2 >>> if(a = 3):
>>> print(a) File "<stdin>", line 1
2 if(a = 3):
>>>b = 6 ^^^^^
>>> a = b+a SyntaxError: invalid syntax. Maybe you
8 meant '==' or ':=' instead of '='?
Operator polymorphism:
A type of polymorphism where an operator behaves differently based on the type
of the operands. Polymorphism means many forms.
Consider + operator:
• Acts as Addition operator if the operands are numbers.
• Acts as Concatenation operator if the operands are strings.
Consider * operator
• Works as Multiplication operator if the operands are numbers.
• Works as Repetition operator if one operand is a string and other operand a Non-
Negative integer
Consider this: -> Boolean literal True represents value 1 and False represents value 0
Point to Think: If more than one operator is there in an expression, how the evaluation
happens? Refer to Lecture #19
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #19
Precedence and Associativity of operators
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Precedence of Operators:
When we have an expression that contains more than one operator and are
different operators, we need to look at the precedence table of operators to decide in
which order the evaluation of an expression must happen. Operator precedence
guarantees a consistent interpretation of expressions.
• Evaluation of 4 + 2 ** 5 // 10
4 + 2 ** 5 // 10 ➝ 4 + 32 // 10 ➝ 4 + 3 ➝ 7
Note: Operator precedence table for Arithmetic Operators has ** at the top. Means it has
highest priority. Binary + and – has the lowest priority.
Likewise every operator in an expression has its precedence set as shown in the table on
Page #5.
Consider 4 + 2 ** 2 // 10. If we want, 4+2 to happen first and then power to 2, please use
parentheses as shown here => ((4 + 2) ** 2)//10
Observe the below outputs from python interpreter.
>>> 4 + 2 ** 2 // 10
4
>>> (4 + 2) ** 2 // 10
3
>>> ((4 + 2) ** 2) // 10
3
Associativity of Operators:
If more than one operator with the same level of precedence exists, rules of
Associativity indicate the order in which an expression is evaluated.
Division and Power operator also do not follow the Associative law. Try it!!
8/4/2 #result is 1.0 (8 / 4) / 2 #result is 4.0
2**3**2 #result is 512 (2**3)** 2 #result is 64
We can use parentheses – ( and ) to prioritize the operators in an expression as per our
wish. But Associativity within the parenthesized expression remains the same.
Precedence and Associativity table for all operators in python
Note: There are so many operators and each of them is specific for its operation. If we
have to know in detail about any operator, please use help() on the operator within
quotes. Screenshot attached.
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #20
Control structures - Selection statements
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
• Sequential Control
A form of control in which instructions are executed in the order that they are
written in the Program. A program consisting of only sequential control is referred
to as a “straight-line program.”
Collectively a set of instructions and the control statements controlling their execution is
called as control structure. This structure is called as the leader suite(body) combination.
Somewhere we need to indicate that the following statements form a group or a block. The
mechanism for grouping is controlled by indentation in python. In case of C language, we
use flower brackets. The leader always ends with “:” and the suite will always have a higher
indentation compared to the leader.
leader:
suite
Sequential Control:
Selection Control:
Here we choose one of the alternates based on the result of condition specified.
Syntax is as below.
Working of if:
The expression specified in the leader of if block is evaluated first.
If it results in True value, then the suite for that if will be executed.
If it is False, then that suite will not be executed. Then it continues with the next statement
which has the indentation same as the leader of if.
Working of if - else:
The expression specified in the leader of if block is evaluated first. If it results in True value,
then the suite for that if will be executed. Else, the suite of else block will be executed. Then
it continues with the next statement which has the indentation same as the leader of if and
else.
Program 1: Program to check whether the two integers entered by the user are equal or
not. Print accordingly.
number_1 = int(input("Enter the first number"))
number_2 = int(input("Enter the second number"))
if number_1 == number_2:
print("Entered numbers are equal.")
else:
print("Entered numbers are not equal.")
Output:
Program 2: Modify the Program to check whether the two strings entered by the user are
equal or not. Print accordingly.
str1 = input("Enter the first string")
str2 = input("Enter the second string")
if str1 == str2:
print("Entered strings are equal.")
else:
print("Entered strings are not equal.")
Output:
Program 3: Program to find whether the number entered by the user is positive, negative
or zero.
num = int(input("Enter the number"))
if (num > 0): # () is optional
print("Entered number", num, "is positve")
elif num == 0:
print("Entered number", num, "is zero")
else:
print("Entered number", num, "is negative")
Output:
Program 4:
a = int(input())
b = int(input())
c = int(input())
if a == b :
if b == c :
print("what?")
else: # paired with the outer if; control reaches here if a not equal to b
print("what else?")
Output: Observe the output when inputs are 1 2 and 3
Program 5: Similar to Program 4. Modified the indentation of else to match with inner if.
a = int(input())
b = int(input())
c = int(input())
if a == b :
if b == c :
print("what?")
else: # paired with the inner if; control reaches here if a equals b and b is not equal to c
print("what else?")
Output: Observe the output when inputs are 1 2 and 3
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
Lecture #21
Control structures - Looping statements
By,
Prof. Sindhu R Pai,
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M (Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Let’s say I want to write a program that simulates the act of waiting for the rain to stop so
that I can go out. How would we wait? We would probably look outside the window
periodically to see if the rain has indeed stopped.
Is it raining? Yes, then stay indoors
Is it raining? Yes, then stay indoors
Is it raining? Yes, then stay indoors
…
…
And the lines go on and on.
Finally, is it raining? No, then go out.
How can we write this in a shorter way?
Now let us write a Program that tells us that it has stopped raining.
raining = True
while(raining):
print(“Stay indoors”)
print(“it has stopped raining, you can go out now”)
Above code results in infinite loop (loop that never terminates or eventually
terminates with a system error) as the expression evaluates to True always.
A while statement can be used to construct both definite and indefinite loops.
Definite Loop
Loop in which the number of times it iterates can be determined before the loop
is executed. Program 3 is an example code which uses the definite loop. Although it is not
known what the value of n will be until the input statement is executed, its value is known
by the time the while loop is reached. Thus, it will execute “n times.”
Indefinite Loop
Loop in which the number of times it iterates cannot be determined before the
loop is executed.
Program 4:
inpt = input("Enter selection: ")
while inpt != 'F' and inpt !='C':
inpt = input("Please enter 'F' or 'C': ")
Output: The number of times that the loop will be executed depends on how many times
the user mistypes the input.
Syntax:
for <target_variable> in <iterable> : # for and in are keywords
<suite/body of for>
Program 5: Given the list which contains 4 elements, print the elements of the list in a
separate line.
numbers = [34,11,23,10]
for val in numbers:
print(val)
Working: The variable val gets the copy of the element 34 in the first iteration and that is
displayed as part of the loop body. In the second iteration, variable val gets the element 11
and displays it. Third and forth iteration, val gets the copy of 23 and 10 respectively and
displays it in the body of its corresponding iteration. When there are no more elements in
the list to be copied to val, the iteration stops.
What if we want to make some changes to the given list in Program 5? Does the below
code work? Let us try to understand in detail.
Program 7: Given a list, Increment the elements of the list by 1 and display the list.
numbers = [34,11,23,10]
print("Original list", numbers)
for val in numbers:
val += 1
print("Same list after for loop execution", numbers)
Output: As the val variable is always a copy of one element at a time from the iterable,
modifying this doesn’t reflect in the given list. Refer to Program 8.
We will discuss the solution to this problem in Program 8 after understanding the
range() function.
>>> list(range(5))
[0, 1, 2, 3, 4]
The function range can take only one argument. The argument is one past the final
value. The default initial value is 0. The step or the common difference is 1.
>>> list(range(5,10))
[5, 6, 7, 8, 9]
The function range can take two arguments. The first argument is the initial value. The
second argument is one past the final value. The step or the common difference is 1.
Points to think!!
• Can we use this range function to generate numbers which can be used as index
to the elements of the list? Yes
• Is there any function to find the number of elements in the iterable? Yes, the
name of the function is len()
>>>numbers = [23,11,66,55]
>>>len(numbers)
4
Program 9: Program to find the square root of all numbers in separate lines from 1 to
n(inclusive).
Hint: sqrt function is available in math module/library. First import math and then use
sqrt with math as the module name.
Usage of functions from module/library - > [Link]() or [Link]()
import math
n = int(input("Enter the max limit: "))
for num in range(1,n+1):
print(num, "->", [Link](num))
Output:
- END -
Lecture Notes
Python for Computational Problem Solving
UE23CS151A
By,
Prof. Sindhu R Pai
Anchor, PCPS - 2023
Assistant Professor
Dept. of CSE, PESU
Verified by,
PCPS Team - 2023
Many Thanks to
Dr. Shylaja S S (Director, CCBD and CDSAML Research Centers, Former
Chairperson, CSE, PES University)
Prof. Chitra G M(Asst. Prof, Dept. of CSE, PCPS Anchor – 2022)
Aug – Dec, 2023
Practice Programs
Try solving these problem statements. Solutions for a few are available in
this link:
[Link]
K/view?usp=drive_link
1. Program to print from 1 to n in separate lines.
2. Program to find the sum of all numbers from 1 to n.
3. Input a string from the user. Print the Unicode of every character in the string in a
separate line.
4. Program to print all odd numbers from 1 to n in separate lines.
5. Program to print all numbers divisible by both 3 and 5 between 1 and n in separate
lines.
6. Program to print all numbers between 1 and n which are ending with 9 in separate
lines.
7. Program to print all numbers from 1 to 10 except 5.
8. WAP to take first name, middle name and last name as input from the user in different
lines and print it on the terminal as one name with spaces.
9. Classify the number entered by the user as even number or odd number. Till user says
stop, he must be able to enter the number for checking its oddness or evenness.
10. Generate n random integers between 1 and 1000.
11. WAP to print all Armstrong numbers from 1 to n. If not available, display proper
message to the user.
Armstrong number is a number, if the sum of its own digits raised to the power
number of digits gives the number itself. For example, 0, 1, 153, 370, 371, 407 are
three-digit Armstrong numbers and, 1634, 8208, 9474 are four-digit Armstrong
numbers and there are many more.
12. Given a number, find whether the number is an Armstrong number or not
14. Program to swap first and last digits of a given number and print the new number.
15. Program to check whether a given number is palindrome or not for any positive
integer. Display appropriate message if the number is –ve.
16. Generate all three digit palindrome numbers.
17. Program to find all Factors of a given number.
18. Program to print all Strong numbers between 1 to n.
Strong number is a special number whose sum of the factorial of digits is equal to
the original number. For Example: 145 is strong number. Since, 1! + 4! + 5!
19. Program to display the hexadecimal and octal version of a given number.
20. Program to enter a number and print its reverse.
21. WAP to print multiplication table of any given number.
22. Given 4 sides and two diagonals of a quadrilateral, classify the quadrilateral as square,
rhombus, rectangle, parallelogram, kite, just quadrilateral.
Requirements: Read four sides and two diagonals. Store in different variables and
convert them to integer values
Conditions:
a. If all sides equal and diagonals equal, display "it is a square"
b. Else if two opposite sides equal and diagonals equal, display "it is a rectangle"
c. else if …
23. Given 3 points A(x1, y1), B(x2, y2) and C(x3, y3), find whether they are collinear. If no,
find the centroid.
Logic: Slope of AB = Slope of BC = Slope of AC
Centroid = ((x1+x2+x3)/3 , (y1+y2+y3)/3)
ii) 1 2 3 4
5678
9 10 11 12
13 14 15 16
26. Given three sides of a triangle, check whether the triangle can be formed or not. If
triangle can be formed, find the type of triangle.
27. Print the lengths of all words in a given string. After the first length, put a decimal point.
Input: May I have a large container of coffee? Expected Output: 3.1415926
28. Program to find the diameter, area and circumference of circle by taking radius as the
input from the user
29. Program to convert the given Decimal number into Binary
30. Program to display sum of odd numbers and even numbers separately between 1 to n.
5. Count the number of factors for a given number and the sum of factors for a given
number.
6. Display the squares of all numbers and the square root of all numbers from 1 to n.
7. Program to display the nth Fibonacci number.
8. Program to display a number from fibonacci series which is just greater than n
9. Program to find the product of three sequential terms from 1 to n.
Hint: If n = 8,
Output: 6, 120,56
10. Display all the numbers from 1 to n except n//2
-END-