0% found this document useful (0 votes)
6 views88 pages

Python Computational Problem Solving Notes

notes

Uploaded by

ganipineedisuhas
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)
6 views88 pages

Python Computational Problem Solving Notes

notes

Uploaded by

ganipineedisuhas
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

Department of Computer Science and Engineering

PES University, Bangalore, India

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

Department of CSE, PESU 2


Aug – Dec, 2023

Types of Computational Problems


▪ Decision Problems
▪ Counting Problems
▪ Search Problems
▪ Sorting Problems
▪ Optimization problems
This semester as a part of the course, we will be dealing with Computational Problem
Solving (CPS). It is evident that in order to solve a problem computationally, we need to
understand the Essence of CPS and the processes involved in CPS.

Essence of CPS

• Representation - Captures all the relevant aspects of the problem.


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

Phases involved the Process of CPS – Refer to Lecture #9 notes


Analysis, Design, Implementation, Testing

Let us solve an example in order to understand the concept of representation and


algorithm.

The Man, Cabbage, Goat and Wolf problem is a River Crossing problem.

Department of CSE, PESU 3


Aug – Dec, 2023

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

Department of CSE, PESU 4


Aug – Dec, 2023

Step 4: Man rows cabbage


Step 4: Man rows wolf across
across
Step 5: Man takes goat back Step 5: Man takes goat back
Step 6: Man leaves goat and Step 6: Man leaves goat and
rows wolf across. rows cabbage across.
Step 7: Man rows back alone. Step 7: Man rows back alone.
Step 8: Man rows goat across. Step 8: Man rows goat across
Step 9: Stop Step 9: Stop

In the above example we are not worried about

• Color of the boat


• Name of the man
• Width of the river
• Freshness of cabbage
• Weight of cabbage
Thus, the only information relevant for this problem is where each particular item is at each
step in problem solving. Therefore, by the use of abstraction, we definea representation
that captures only this needed information.

- END -

Department of CSE, PESU 5


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Limits of Computational Problem Solving:


Computational Problem Solving depends on many factors like:
• Complexity of the Problem:
Related to the space and time tradeoff.
• Efficiency of an Algorithm
Related to the fastness and accuracy of the result.
• Available Computing Resources
Resources availability might be enormous or very limited.

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.

Department of CSE, PESU 2


Aug – Dec, 2023

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 -

Department of CSE, PESU 3


Department of Computer Science and Engineering
PES University, Bangalore, India

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.

Department of CSE, PESU 2


Aug – Dec, 2023

Few Types of Number systems are listed below:


• Binary number system (Base - 2)
Digits allowed: 0 and 1
• Octal number system (Base - 8)
Digits allowed: 0 to 7
• Decimal number system (Base - 10)
Digits allowed: 0 to 9
• Hexadecimal number system (Base - 16)
Digits allowed: 0 to 9 and A to F (10 to 15)

Problem 1: Provide the binary equivalent of a given decimal number – 53.

Read from last to first. Solution is 110101(2)

Problem 2: Provide the decimal equivalent of a given binary number – 110101


1×2^5 + 1×2^4 + 0x2^3 + 1×2^2 + 0x2^1 + 1×2^0 = 53
Solution is 53(10)

Department of CSE, PESU 3


Aug – Dec, 2023

Computer is composed of Hardware and Software components.


Hardware Components:
Comprises of physical parts of a Computer 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).

Department of CSE, PESU 4


Aug – Dec, 2023

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 -

Department of CSE, PESU 5


Department of Computer Science and Engineering
PES University, Bangalore, India

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.

Types of Software Components are as below:


• System software: Intrinsic to the System
Operating System – software that manages and interacts with the hardware
resources of a computer. It is a set of encoded information or computer instructions. It does
the job of recognizing the input from the keyboard and mouse and displaying the output on
the screen. Keeps track of files and directories on the disk and controls peripheral devices
• Application software: A specific purpose software which is used by user for
performing specific task.
Examples - Cyberghost, Antivirus, Folderlock, Flash player, Browsers, Photoshop,
7zip, notepad++

Department of CSE, PESU 2


Aug – Dec, 2023

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.

System Software Application Software


Used for operating computer Used by user to perform specific
hardware. task.
Installed on the computer when Installed according to user’s
operating system is installed requirements.
User does not interact with
User interacts with application
system software because it
softwares.
works in the background.
Can run independently. It Can’t run independently. They can’t
provides platform for running run without the presence of system
application softwares. software.
Examples: compiler, assembler, Examples: word processor, web
debugger, driver, etc. browser, media player, etc.

- END -

Department of CSE, PESU 3


Department of Computer Science and Engineering
PES University, Bangalore, India

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.

Program Translation: Refer to Lecture #9 notes.

- END -

Department of CSE, PESU 2


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Process of Computational Problem Solving


Computational problem solving does not simply involve the act of computer
programming. It is a process, with programming being only one of the steps. Before a
program is written, a design for the program must be developed. And before a design can
be developed, the problem to be solved must be well understood. Once written, the program
must be thoroughly tested.

Phases involved in the process of Computational Problem Solving

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

Department of CSE, PESU 2


Aug – Dec, 2023

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

Department of CSE, PESU 3


Aug – Dec, 2023

Interpreter: Converts high-level language to machine language line by line and


execute instructions in place of CPU.

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 -

Department of CSE, PESU 4


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Few points to think!


• How do you communicate with the computer?
• How do you provide instructions to the computer to do our job?
• Which language do you use to give the instructions to computer?

Introduction to Programming Language


Language is the primary mean of communication and human interaction for
thousands of years. Similarly, we need a language to communicate with computers. It has
hardware and software that need to communicate with each other. Your application is
reacting to the mouse and keyboard or even the mic, it can read files from your disk storage
and so on. But at the end of the day, the machine understands bits, 1s, and 0s, the
combination of which creates meaning. It is obvious that we find it difficult to communicate
to the computer in their language. Hence, we would use a language which makes it easier
for us to express our ideas means the language which is closer to the way we perceive.

Programming language: Provides the necessary constructs to instruct the


computer to do the tasks/jobs for us.
Program: A sequence of instructions used to “instruct the computer to
perform various tasks”.
Note: Programming is an art/creative activity.

Levels of Programming Languages:


• Low Level
- Binary codes which CPU executes
- Programmer’s responsibility is more
- Eg. Machine language
• Middle Level
- Offers basic data structure and array definition, but the programmer should

Department of CSE, PESU 2


Aug – Dec, 2023

take care of the operations.


- Eg. C and C++
• High Level
- Programmer concentrates on the algorithm and programming itself
- Eg. Java, Python, Pascal

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.

Paradigms of Programming Languages


• Imperative
• Structured Programming
• Procedural
• Declarative
• Functional
• Logical
• Object-Oriented

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

Department of CSE, PESU 3


Aug – Dec, 2023

that the TIOBE index is not about the best programming language or the language in
which most lines of code have been written.

Refer to this link for more details: TIOBE Index - TIOBE


Average positions of top 5 languages for a period of 12 months is given below.

Introduction to Python Language


High Level Language developed by Guido van Rossum is published in Feb 1991. It is
named after Monty Python circus Show- a satirical show aired on BBC in the 60s and 70s.
It is a simple yet powerful language well received by both the academia and the industry.

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.

Department of CSE, PESU 4


Aug – Dec, 2023

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

Department of CSE, PESU 5


Aug – Dec, 2023

comprehensions.
• Automatic memory management feature of python frees you from having to
manually allocate and free memory in your code.

- END -

Department of CSE, PESU 6


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Few points to think!


• What must be installed to run the code written in python language?
Hybrid Python interpreter/Compiler
• Which version of python must be used?
The stable version – Python 3.X and above.
Refer to [Link] – An official site for python

Links for installation of python on different OS:


• Windows : How to install Python 3.11.0 on Windows 10 - Bing video
• MAC: How to Install Python on Mac OS and How to Run Python code - YouTube

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

Running the python Code


There are different ways of making the computer follow the commands of Python.
• Interactive mode
• Batch Mode / File Mode / Script Mode
• IDE Mode – IDLE Installation and Usage is a part of Lab.

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 (>>>).

Department of CSE, PESU 2


Aug – Dec, 2023

- Here only python commands are valid.

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

- Save the above file. Close the editor.


- Run them together using the python interpreter on the created python file(.py
extension conventionally) - python [Link]
- You can see the output if there are no errors.

Department of CSE, PESU 3


Aug – Dec, 2023

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.

Department of CSE, PESU 4


Aug – Dec, 2023

First Program in Python:


Open the command prompt / terminal.
Open the Editor. Save the code with .py extension. Run it
Interpreter Mode Execution:

Batch Mode Execution: python 1_first.py

- END -

Department of CSE, PESU 5


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Output Function – print:


Consider the below executions.
Interpreter mode

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

Department of CSE, PESU 2


Aug – Dec, 2023

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.

Characteristics of print function:


• Can display/print anything in the world.
• Can take any type of arguments.
Values could be Numbers, Boolean, strings, collections, expressions, functions,
etc.
• Can take any number of arguments.
• Has the capability to evaluate the expression.
• Formatting is possible to some extent using the keyword separators – sep & end

Department of CSE, PESU 3


Aug – Dec, 2023

Few Examples:
Example 1: Can take any type of arguments

Example 2: Can take any type of arguments of any type

Example 3: Can be used to evaluate the expression

Department of CSE, PESU 4


Aug – Dec, 2023

Example 4: Batch Mode executions

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:

Few points to note in Example 5:


The sep and end field behavior is only applicable for the print function in which
it is specified. The subsequent print function calls will use its default value as per the
help page of print.

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.

Department of CSE, PESU 5


Aug – Dec, 2023

Example 6:

- END -

Department of CSE, PESU 6


Department of Computer Science and Engineering
PES University, Bangalore, India

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.

Department of CSE, PESU 2


Aug – Dec, 2023

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!

Program 3: This code results in Error as and is a keyword.


and = 10
print(and)

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.

Department of CSE, PESU 3


Aug – Dec, 2023

Think about it: Can we use sep and end as a variable?


Program 4:

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

Department of CSE, PESU 4


Aug – Dec, 2023

String literals or string:


• A sequence of characters denoted by a pair of matching single or double (and

sometimes triple) quotes in Python.

Valid Literal examples are below.

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.

Categories of types: Scalar type and Reference Types


Scalar Types: Simple ones which have a single value.

Department of CSE, PESU 5


Aug – Dec, 2023

Reference types:
Structured or reference types having more than one value.

- END -

Department of CSE, PESU 6


Department of Computer Science and Engineering
PES University, Bangalore, India

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.

Note: In python 3.x and above, value returned by input() is a string.

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.

Type conversion functions must be used if required.

Department of CSE, PESU 2


Aug – Dec, 2023

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.

Solution Version -2:


length = int(input("Enter the length of the rectangle"))
breadth = int(input("Enter the breadth of the rectangle"))
print(length+breadth+length+breadth)

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?

Department of CSE, PESU 3


Aug – Dec, 2023

Here comes the usage of eval function .

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 -

Department of CSE, PESU 4


Department of Computer Science and Engineering
PES University, Bangalore, India

Lecture Notes
Python for Computational Problem Solving
UE23CS151A

Lecture #17 and 18


Operators and Expressions

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

Operators and expression

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.

Expression: A valid combination of operators and operands which evaluates to a value is


called as expression. Examples of expression are mentioned here.
• Constants / Literals
1234.67, “python”, -23
• Variables
a = 45 # a is an expression but a= 45 is not an expression but a statement
• Any Operations on literals and variables
5+6, 2/2, a > 2 & b <= 5

Few points to note:


o An expression has a value. Statement does not have a value.
o An expression is also a statement. A statement is not necessarily an
expression.
o Assignment is not an expression. a1 = 5 is just a statement

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.

Department of CSE, PESU 2


Aug – Dec, 2023

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

Arithmetic Operators: Addition(+), Subtraction(-), Multiplication(*), Division(/),


Truncation Division(//), Remainder(%), Exponentiation(**)
For testing some of the operators and expressions, use the interpreter mode of python
prompt as below.
>>> 25 / 4 #True Division
6.25
>>> 25 // 4 #Truncation division or Integer Division. 25 is the dividend, 4 is the
divisor, perform division and integer quotient is the result.
6
>>> 25 % 4 #25 is the dividend, 4 is the divisor, result is the remainder after
performing integer division
1
>>> 25 ** 3 #25 power 3
15625

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.

Consider the below statements. And see what is happening here?


print(25 / 4, 25 % 4, 25 // 4, 27 // 4, -25 // 4, -27 // 4)
# 6.25 1 6 6 -7 -7
print(25.8 % 4.2) # modulus operator works on float values in python
# 0.6

Department of CSE, PESU 3


Aug – Dec, 2023

While using truncation division(//), note these points:


• When both operands are integer values, the result is a truncated integer referred
to as integer division. Example: 40//10 evaluates to 4
• When at least one of the operands is a float type, the result is a truncated floating
point. Example: 44.0//10 evaluates to 4.0

Relational Operators: <, <=, >, >=, ==, !=


These are used to compare two values. The result is of bool type with values True
and False. For testing some of the operators and expressions, use the interpreter mode of
python prompt as below.
>>> 3 > 1
True
>>> 3 >= 3
True
>>> 3 > 3
False
>>> 2.7 < 10.4
True
>>> 2 == 2
True
>>>2 != 2
False
>>> print( 3>=3.0<2.5)
False

Consider the below statements. And see what is happening here?


print(10 == 10) #True
print(3 > 2) #True
print(3 > 2 > 1) #True . This is known as cascading of operations.

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

Department of CSE, PESU 4


Aug – Dec, 2023

Logical Operators: and, or, not


This is used to construct arbitrarily complex Boolean expressions. Hence, the other
name for Logical operators is Boolean operators.

These operators work on Boolean values and Boolean equivalent values

• 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

Department of CSE, PESU 5


Aug – Dec, 2023

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

& Operator ^ Operator << Left Shift Operator


a=5 # 0101 a=5 # 0101 a=5 # 0101
b=6 # 0110 b=6 # 0110 b = a << 2 # 010100
c=a&b # 0100 (4) c=a^b # 0011 (3)

| Operator ~ One’s complement


a=5 # 0101 a=5
b=6 # 0110 print ( "~ a ", ~a )
c=a|b # 0111 (7) # 1111111111010 => -6 >> Right Shift Operator
A general rule of thumb is a=5 # 0101
~x = -(x+1) b = a >> 2 # 0001

Department of CSE, PESU 6


5
Aug – Dec, 2023

>>> 4 & 8 >>> 10 // (2**3)


0 1
>>> 4 | 8 >>> 10 << 3
12 80
>>> 4 ^ 8 >>> 10 * (2**3)
12 80
>>> 10 >> 3 >>> ~5
1 -6
>>> 10 / (2**3) >>> ~-6
1.25 5

Membership Operators: in, not in


These operators can be used to determine if a particular value occurs within a
specified collection of values.
>>> 11 in [23,44,"pai",11,0,"sindhu"]
True
>>> '11' in [23,44,"pai",11,0,"sindhu"]
False
>>> "s" in "sindhu"
True
>>> print("app" in "whatsapp") #True
True
>>> print("pap" in "whatsapp") #checks for the string "pap" in "whatsapp". Not the
character p and a and p
False
>>> print("pap" not in "watsapp")
True

Identity Operators: is, is not


Checks if the operands on either side of the operator point to the same object ornot.
It compares the ids of both the operands.
>>> 6 is 6
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> 6 is not 6
<stdin>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
False
>>> 6 is not 7
<stdin>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
True

Department of CSE, PESU 7


Aug – Dec, 2023

>>> 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 '='?

Shorthand Operators: += , -=, *= , /= , //= , %= , **=


It combines arithmetic and assignment operators.
Expression Short Hand >>> a = 5
a=a+b a += b >>> a += 10
>>> a
a=a-b a -= b
15
a=a*b a *= b >>> b = 7
a=a/b a /= b >>> a -= b
>>> a
a = a // b a //= b 8
a=a%b a %= b >>> a **= 2
a = a ** b a **= b >>> a
64

Department of CSE, PESU 8


Aug – Dec, 2023

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

Department of CSE, PESU 9


Aug – Dec, 2023

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

Department of CSE, PESU 10


Department of Computer Science and Engineering
PES University, Bangalore, India

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 and Associativity of Operators

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.

Let us consider the following examples of Arithmetic Expression -


• Evaluation of 4 + 3 * 5
There are two possible ways in which it can be evaluated 4 + 3 * 5 ➝ 4 + 15 ➝ 19
Or 4 + 3 * 5 ➝ 7 * 5 ➝ 35. To ensure that the results will be the same at all times, we use
the rules of operator precedence.

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

Priority Operators List


1 **
2 Unary + and -
3 *, /, //, %
4 Binary + and -

Likewise every operator in an expression has its precedence set as shown in the table on
Page #5.

It is a good programming practice to use parentheses to know about your precedence of


operators in an expression.

Department of CSE, PESU 2


Aug – Dec, 2023

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.

Let us consider the following examples of Arithmetic Expression –


• Evaluation of 2 + 3 + 4
There are two possible ways in which it can be evaluated. (2 + 3) + 4 or 2 + (3 + 4) ➝ 9.
Addition operator follows the Associative Law. Hence the order of evaluation doesn’t
matter.
• Evaluation of 8 - 4 – 2
This can be evaluated as (8 - 4) – 2 -> 4 – 2 -> 2 or 8 – (4 - 2) -> 8 – 2 -> 6.
Subtraction operator doesn’t follow the Associative Law. Hence the Associativity table
makes sense. As the subtraction is Left to right, the result of above expression is 2.
Operators
Priority Associativity
List
1 ** Right to Left
2 Unary + and - Left to Right
3 *, /, //, % Left to Right
4 Binary + and - Left to Right

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

Department of CSE, PESU 3


Aug – Dec, 2023

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

Department of CSE, PESU 4


Aug – Dec, 2023

Ref: Precedence and Associativity of Operators in Python - GeeksforGeeks

Department of CSE, PESU 5


Aug – Dec, 2023

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 -

Department of CSE, PESU 6


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Control Structures in Python


Control flow is the order in which instructions are executed in a program. A control
statement is a statement that determines the control flow of a set of instructions. There
are three fundamental forms of control that a python language provides:

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

• Selection Control / Branching Control/ Conditional Control


This is provided by a control statement that selectively executes instructions based on
a given condition.

• Iterative Control / Repetitive Control


This is provided by a control statement that repeatedly executes instructions
based on a given condition.

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:

Department of CSE, PESU 2


Aug – Dec, 2023

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.

Department of CSE, PESU 3


Aug – Dec, 2023

Working of if – elif - 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. Then it exits the if –elif-else ladder and continues
with the next statement which has the indentation same as the leader of if. If the evaluated
expression in if results in False value, the expression specified in the elif will be evaluated. If
this results in True value then it’s block will be executed. Else it evaluates the expression of
next elif until one of the elif expression is resulting in True. If none of the elif expressions
resulted in True value, the suite of else will be executed. Then it exits the if –elif-else ladder
and continues with the next statement which has the indentation same as the leader of if.
In any case only one suite will be executed for which the leader expression resulted in
True value. It is not mandatory to have else block with if-elif.

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:

Department of CSE, PESU 4


Aug – Dec, 2023

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")

Department of CSE, PESU 5


Aug – Dec, 2023

Output:

Dangling Else Problem:


If there are two ifs and a single else, to which if should we associate the else? - This is
called dangling else problem. In Python, the solution is that else matches if with the same
indentation as else.

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

Department of CSE, PESU 6


Aug – Dec, 2023

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 -

Department of CSE, PESU 7


Department of Computer Science and Engineering
PES University, Bangalore, India

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

Control Structures in Python


Looping constructs in Python
Also considered as Iterative Control / Repetitive Control. This is provided by a
control statement that repeatedly executes instructions based on a given condition. In
python, we have while, for and do - while keywords available for looping.

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?

Consider the looping construct while and the algorithm as below.


while it is still raining
stay indoors

There are 3 ingredients to any iterative statement:


• Initial value of the iterative counter or condition
• Final Iterative condition
• Updating the iterative counter or condition in order to reach the final iterative condition

Department of CSE, PESU 2


Aug – Dec, 2023

while: It is an iterative control statement that repeatedly executes a set of statements


based on an expression provided. If the expression evaluates to True value, suite will be
executed and control comes back to expression again. Again, suite will be executed
based on the output of expression and this goes on till the expression is evaluated to
False. Once the expression evaluates to False, control exits from the loop.
Syntax:
while expression: #while is a keyword
Statement(s) #suite of while

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”)

Program 1: Write a program to print the numbers from 1 to 10 in different lines


i=1
while i < 11:
print(i)
print(“end of loop”)
Output:

Above code results in infinite loop (loop that never terminates or eventually
terminates with a system error) as the expression evaluates to True always.

Department of CSE, PESU 3


Aug – Dec, 2023

Program 2: Modification of Program 1 to get required output.


i=1
while i < 11:
print(i) # prints and increment the value of variable i by 1
i += 1 #Shorthand operator usage
print(“end of loop”)
Output:

Program 3: Program to find the sum of first n natural numbers.


n = int(input("Enter n-->"))
i=1
sum = 0
while i <= n:
sum += i
i += 1 #i++ not available in python. No decrement and no increment operators
print("sum is", sum)
Output:

A few points to think about Program 3.


• Can sum be a variable?
• Can we use only sum and n avoiding the extra variable i?
• If program 3 is saved as [Link], when we open the file in notepad++, the color
of sum and the color of print is same. Any specific reason behind this?

Department of CSE, PESU 4


Aug – Dec, 2023

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.

for : It is an iterative control statement that works exclusively on collections. It


examines each element and performs any action set by the programmer until there are
no more elements left in the collection. Use for when the number of times we execute
the body or the suite is determinable.

Department of CSE, PESU 5


Aug – Dec, 2023

Syntax:
for <target_variable> in <iterable> : # for and in are keywords
<suite/body of for>

An iterable is a collection of elements physically or conceptually. It has a builtin


mechanism to give an element each time we ask and it has a builtin mechanism to signal
when there are no more elements.

Semantics of ‘for’ is as below.


1. Start iterating through the iterable.
2. Get one element to the target variable as a copy.
3. Execute the suite or the body.
4. Repeat steps 2 and 3 until the iterable signals that it has no more elements.
5. Exit the for loop and move to the next statement.

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.

Department of CSE, PESU 6


Aug – Dec, 2023

Program 6: Print the characteristics of a given string in a separate line.


str1 = "sindhu cse pesu"
for s in str1:
print(s)
Output:

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.

Department of CSE, PESU 7


Aug – Dec, 2023

range: The range is a builtin function, that generates numbers in an arithmetic


progression and creates a range object. help(range) is as below.

Characteristics of range function:


• When we call / invoke the range function, it doesn’t return the list itself. Rather,
it returns a conceptual collection of values.
• It is a Lazy function - The values come into existence only when we explicitly ask
for it. It knows what it is supposed to do, and does it only when it is forced to
produce some result.
• The function returns an iterable object that can be used in a for loop or can be
converted / extracted into a list, set or tuple
Note: Many functions producing lots of outputs are made lazy in Python 3.x. The lazy
functions use less space compared to eager functions. The lazy ones may be more
efficient if we do not use all the results generated by the function.

Let us use some variations of range and try understanding it.


>>> range(1, 10, 2)
range(1, 10, 2)
This output tells us that the result to call of range is an arithmetic progression
with the initial value 1, the common difference 2 and the final value is less than 10. As
we can see, the sequence itself is not displayed. It conceptually holds all the elements.
To get all the elements from this conceptual box, iterate through using different ways as
shown below.

Department of CSE, PESU 8


Aug – Dec, 2023

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

>>> list(range(5,15, 2))


[5, 7, 9, 11, 13]
The function range can take three arguments. The first argument is the initial value. The
second argument is one past the final value. The third argument is the step or the
common difference.

Few more FYA : Self explanatory.

Department of CSE, PESU 9


Aug – Dec, 2023

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 8: Solution to Program 7 using range() and len()


numbers = [34,11,23,10]
print("Original list", numbers)
for i in range(len(numbers)):
numbers[i] += 1
print("Same list after for loop execution", numbers)
Output:

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))

Department of CSE, PESU 10


Aug – Dec, 2023

Output:

- END -

Department of CSE, PESU 11


Department of Computer Science and Engineering
PES University, Bangalore, India

Lecture Notes
Python for Computational Problem Solving
UE23CS151A

Lecture #22, #25, #26


Problem Solving using Control Structures
Practice Session + Revision

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

Department of CSE, PESU 2


Aug – Dec, 2023

13. Display whether a given number is perfect number or not.


A perfect number is a positive integer that is equal to the sum of its positive
divisors, excluding the number itself.

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)

24. For a given n, display as below. Example n = 4


a
ab
abc
abcd

Department of CSE, PESU 3


Aug – Dec, 2023

25. Given n, display the following (say 4)


i)1 0 0 0
0100
0010
0001

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.

Few more listed below:


1. Display Snake - Ladder Game chart
2. Program to calculate the LCM of two numbers.
3. Sumedh offers a discount of 10% on the cost price of the TV unit. TV unit price is
35000 . What is the selling price of a TV unit?
4. A shop will give a discount of 10% if the cost of the quantity purchased is more
than 1000. Ask the user for quantity. Suppose, one unit will cost 100. Judge and print
total cost for the user.
i. quantity = int(input("Enter the number of quantities"))
ii. if (quantity*100 > 1000):
1. print ("Cost is",((quantity*100)-(.1*quantity*100)))
iii. else:
1. print ("Cost is",quantity*100)

Department of CSE, PESU 4


Aug – Dec, 2023

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-

Department of CSE, PESU 5

You might also like