PSPP_Unit 1 Notes_25-09-2024.
PSPP_Unit 1 Notes_25-09-2024.
UNIT-I
Syllabus (UNIT – I):
Techniques of Problem Solving: Algorithms, Flowcharts, Decision Table, Programming methodologies viz. top-
down and bottom-up programming.
Software requirements for programming: Operating System, Editor (IDE), Compiler, Linker, Loader.
Introduction to Python: Structure of a Python Program, Python program execution steps, Python Interpreter
and Script mode of programming, Lines and Indentation, Identifiers and keywords, Literals, Python suite,
comments, quotation in python.
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of solutions.
The problem solving process starts with the problem specifications and ends with a correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a problem.
Problem solving can be expressed in the form of
● Algorithms.
● Flowcharts.
● Programs
ALGORITHM
It is defined as a sequence of instructions that describe a method for solving a problem. In other words it is a
step by step procedure for solving a problem
PROBLEM SOLVING AND PROGRAMMING USING PYTHON(22CSC40N) - D RAVI, ASSISTANT PROFESSOR, MED
Building Blocks of Algorithm
As algorithm is a part of the blue-print or plan for the computer program. An algorithm is constructed using
following blocks.
● Statements
● States
● Control flow
● Function
Statements:
Statements are simple sentences written in algorithm for specific purpose. Statements may consists of
assignment statements, input/output statements, comment statements Example:
Read the value of ‘a’ //This is input statement
Calculate c=a+b //This is assignment statement
Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.
States:
An algorithm is deterministic automation for accomplishing a goal which, given an initial state, will terminate in
a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow:
Control flow which is also stated as flow of control, determines what section of code is to run in program at a
given time. There are three types of flows, they are
● Sequential control flow
● Selection or Conditional control flow
● Looping or repetition control flow
PROBLEM SOLVING AND PROGRAMMING USING PYTHON(22CSC40N) - D RAVI, ASSISTANT PROFESSOR, MED
Selection or Conditional control flow:
Selection flow allows the program to make choice between two alternate paths based on condition. It is also
called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two numbers.
Example:
Description: finding the greater number
1. Start
2. Read a
3. Read b
4. If a>b then
5. Print a is greater
6. else
7. Print b is greater
8. Stop
PROBLEM SOLVING AND PROGRAMMING USING PYTHON(22CSC40N) - D RAVI, ASSISTANT PROFESSOR, MED
Flowchart:
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes, diamonds, and
other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
4. Only one flow line should come out from a process symbol.
5. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible
answer, cap leave the decision symbol.
2. If flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines.
3. Ensure that flowchart has logical start and stop.
Advantages of Flowchart :
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis:
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation:
Flowcharts are used for good program documentation, which is needed for various purposes.
Efficient Coding:
The flowcharts act as a guide or blue print during the system analysis and program development phase.
Systematic Testing and Debugging:
The flowchart helps in testing and debugging the program
Efficient Program Maintenance:
The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer
to put efforts more efficiently on that part.
Disadvantages of Flowchart:
Complex Logic:
Sometimes, the program logic is quite complicated. In that case flowchart becomes complex and difficult
to use.
Alteration and Modification:
If alterations are required the flowchart may require re-drawing completely.
Reproduction:
As the flowchart symbols cannot be typed, reproduction becomes problematic.
Example:
How to Create a Login Screen Decision Base Table
Let's make a login screen with a decision table. A login screen with E-mail and Password Input boxes.
The condition is simple − The user will be routed to the homepage if they give the right username and password.
An error warning will appear if any of the inputs are incorrect.
Username (T/F) F T F T
Password (T/F) F F T T
Output (E/H) E E E H
Legend
● T - Make sure your login and password are correct.
● F - Incorrect login or password
● E - An error message appears.
● H - The home screen appears.
Interpretation
● Case 1 − Both the username and password were incorrect. An error message is displayed to the user.
● Case 2 − The username and password were both right, however, the password was incorrect. An error
message is displayed to the user.
● Case 3 − Although the username was incorrect, the password was accurate. An error message is displayed
to the user.
● Case 4 − The user's username and password were both accurate, and the user went to the homepage.
.
Programming methodologies:
Python supports various programming methodologies, each suited to different types of projects and problem-
solving approaches. Here are the key programming methodologies commonly used in Python:
1. Procedural Programming:
Focuses on a step-by-step approach where the program is divided into procedures or functions. Each function
performs a specific task.
Use Case: Suitable for small to medium-sized programs where tasks can be broken down into functions.
Example:
result = add(5, 3)
print(result)
# Output: 8
3. Functional Programming:
Treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
It emphasizes the use of pure functions, higher-order functions, and recursion.
Use Case: Useful for tasks that involve heavy mathematical computations, data transformations, or require a
declarative approach.
Example:
4. Modular Programming:
Divides a program into separate modules or components, each with a specific responsibility. These modules
can be developed, tested, and debugged independently and then integrated.
Use Case :Helps manage complexity in large projects by organizing code into reusable modules.
Example:
5. Declarative Programming
● Description: Focuses on what the program should accomplish without specifying how. This includes domain-specific
languages or frameworks.
● Example: SQL for querying databases or regular expressions for pattern matching.
● Example Code (using a list comprehension):
Example:
6. Concurrent Programming
● Description: Focuses on executing multiple tasks concurrently to improve performance and responsiveness.
● Example: Using threading or asynchronous programming to handle multiple tasks.
● Example Code (using asyncio for asynchronous programming):
Example:
Each of these methodologies can be used independently or combined depending on the needs of the project.
Approaches to Problem Solving:
● Top-Down Approach
The idea of the top-down approach is to divide a complex problem into smaller sub-problems, this process
is also called decomposition. The sub-problems are further divided into sub-problems and this process is
continued until each sub-problem is atomic (Can’t be divided further) and can be solved independently of
other sub-problem
Structured programming languages, like C programming use the top-down approach to solving a problem
in which the flow of control is in the downward direction.
● Bottom-Up Approach
In this approach, we start working from the most basic level of problem solving and moving up in
conjugation of several parts of the solution to achieve the required results. The most fundamental units,
modules and sub-modules are designed and solved individually, and these units are then integrated
together to get a more concrete base for problem solving. This bottom-up approach works in different
phases or layers. Each module designed is tested at a fundamental level and integration of the individual
modules is done to get the solution.
Object Oriented Programming languages like the C++ or Java uses bottom-up approach to solving a problem
in which the flow of control is in the upward direction
Bottom-up Approach Vs Top-down Approach:
Interaction Bottom-Up model have high interactivity Top-down model has tight coupling
4 between various modules. issues and low interactivity between
various modules.
Approach Bottom-up model is based on composition Top-down model is based on
5
approach. decomposition approach.
Issues In Bottom-Up, some time it is difficult to In Top-Down, it may not be possible to
identify overall functionality of system in break the problem into set of smaller
6
initial stages. problems.
NOTE: The top-down approach is the conventional approach in which the decomposition of the
higher-level system into a lover-level system takes place respectively while the bottom-up approach starts
by designing lower abstraction modules and then integrating them into a higher-level system
Software Requirements for programming:
An operating system is a program which connects the user and the electronic hardware
in a computer.
It has a set of programs which supervise the activities of a computer and control the operations of the hardware
components such as CPU, main memory, disk drives, keyboard, monitor printer and so on.
As the name suggests, an operating system is a type of software without which you cannot operate or
run a computer. It acts as an intermediary or translation system between computer hardware and application
programs installed on the computer. In other words, you cannot directly use computer programs with computer
hardware without having a medium to establish a connection between them.
Besides this, it is also an intermediary between the computer user and the computer hardware as it
provides a standard user interface that you see on your computer screen after you switch on your computer.
For example, the Windows and the Mac OS are also operating systems that provide a graphical interface with
icons and pictures to enable users to access multiple files and applications simultaneously.
● Application software is broken into two classes: general-purpose software and application-
specific software.
● General-purpose software is purchased from a software developer and can be used for more
than one application. Examples of general-purpose software include word processors,
database management systems, and computer-aided design systems. They are labeled
general purpose because they can solve a variety of user computing problems.
● Application-specific software can be used only for its intended purpose. A general ledger
system used by accountants and a material requirements planning system used by a
manufacturing organization are examples of application-specific software. They can be used only
for the task for which they were designed; they cannot be used for other generalized tasks.
EDITOR (IDE):
In Python programming, Integrated Development Environments (IDEs) are essential tools that help you
write, debug, and run code more efficiently. Here are some popular Python IDEs:
1. PyCharm:
Features:
● Code completion and error highlighting.
● Integrated debugger and testing.
● Version control system (Git, SVN).
● Supports web development frameworks like Django and Flask.
● Built-in terminal.
Best for: Professional developers working on large projects.
4. Spyder:
Features:
● Specifically designed for data science with integrated tools like IPython console, variable explorer, and
plotting.
● MATLAB-like interface.
● Integrated debugging and profiling.
Best for: Data scientists and researchers who need a powerful data analysis environment.
5. IDLE:
Features:
● Comes with Python by default.
● Simple interface, ideal for beginners.
● Integrated shell and basic debugging.
Best for: Beginners looking for a basic environment to start coding in Python.
PROGRAMMING LANGUAGES
Programming language can be defined as , the language used for expressing a set of instructions that can
be executed by the computer.
Where opcode specifes the operation to be performed over one or more operands
Ex : To find the sum of two numbers a=12 and b=9, the instruction is as follows.
10001 1100 1001
Where 10001 denotes addition operation
1100 and 1001 denote operands a and b
v) These languages do not require translators because machine code will be directly
understood by the computer.
Limitations:
1) These languages are machine dependent.
2) Lack of readability.
2. Assembly level languages (ALLs)
i) Programming in low-level languages is very difficult. Therefore middle-level languages are
developed. These are also called second generation languages.
ii) The instructions of these languages consists mnemonics. Mnemonics are the English
like abbreviations to represent the elementary operations of the computer.
Example:
To find the sum of two numbers a=12 and b=9, the code is as follows
LOAD A
ADD B
STORE
C
iii) Assembly languages require translator programs, called assemblers. Assemblers convert
assembly language programs machine level languages.
Assembler
C = A + B;
iii) Translator programs called compilers/Interpreter convert high-level language programs
to machine language.
iv)Compiler/interpreter is a system program, which converts a HLL program into its MLL
equivalent. A program written in a HLL is called a Source Program and the machine code
obtained after conversion is called Object Program.
HLL
Compiler
Equivalent MLL
v) BASIC, PASCAL, COBOL, FORTRAN,C and C++ are the high level languages.
vi) HLL are more readable and easy to understand and modify if need be.
vii) HLL are portable i.e they are machine independent.
Assembler is software that converts a program written in assembly language into machine code.
There is usually one-to-one correspondence between simple assembly statements and machine
language instructions. Since the machine language is dependent on the processor architecture,
assembly language programs also defer for different architecture.
Interpreter:
Interpreter performs line by line execution of the source code. Interpreter reads source code line
by line, converts it into machine understandable form, executes the line, and then proceeds with
the next line. Some languages that uses interpreter are BASIC and PYTHON
Compiler:
A program written in high level language has to be converted to a language that computer can
understand i.e. binary form. Compiler is software that translates the program written in high level
language to machine language. The program written in high level language is called source code
and the compiled program is called object code.
The compilation process generally involves two parts. Breaking down the source code into
small pieces and constructing the object code. The compiler also reports syntax errors, if any in
the source program.
Assembler
Source code Object code
Interpreter
Compiler
Linker:
A linker is a program that link several object modules and libraries to form a single executable
program.
Loader:
Loaders are a part of operating system that brings an executable file residing on disk into
memoryand starts it running.
Source
Object
program Compiler code Linker
Loader Executable
Memory code
INTRODUCTION TO PYTHON:
History of Python:
3.12--latest Version
We must download and install Python 3.12.6 from www.python.org.
Features of Python:
Features of a language are nothing but Services or Facilities provided by Language.
Developers and these features are used by Language Programmers for developing Real Time
Applications.
2. Python Programming Provides in-built "Garbage Collection Facility” and collects Un-used
Memory Space and improves the performance of Python Based Applications.
Define of Garbage Collector:
A Garbage Collector is one of the background unbuilt python program, which is running behind of
regular python program and whose purpose is that to collect Un-used
Memory Space and improves the performance of Python Based Applications.
Hence Python Garbage Collector provide automatic Memory Management.
3. Python Programming User-Friendly Syntaxes. So that Python Programmers can develop Error-Free
Programs in limited span time.
FreeWare:
A language or Software is said to be FreeWare if and only if Which is Freely Downloaded.
Example: Java, Python...etc
Open Source:
The Customization of standard Software is called Open Source.
The standard name of Python Software is "CPYTHON".
Some of the Software Vendors came forward and Customized CPYTHON and the customized versions of
CPYTHON are used In-hues tool those software Companies.
=>The Customized Versions of CPYTHON are called "Python Distributions".
● In IT, "Platform" is nothing but type of OS Being Used to run the application.
● In IT, we have two Types of Programming Languages. They are
Examples: C,CPP...etc
A Language is said to Platform Independent if whose OBJECTS takes Same memory space on All Types
OSes and There Restriction on size of Data which is present in object(Behind of objects there exist class).
(Python Slogan)
4. Dynamically Typed:
=>In context Programming, We have Two Types of Programming Languages. They are
Examples:
int a,b,c; // Variable Declaration
a=10
b=20
c=a+b
Examples: C,C++,JAVA, .NET...etc
5. Interpreted Programming:
● When we develop any python program, we must give some file name with an extension .py (File
Name.py).
● When we execute python program, two process taken place internally
a) Compilation Process
b) Execution Process.
In COMPILATION PROCESS, The python Source Code submitted to Python Compiler and It reads the
source Code, Check for errors by verifying syntaxes and if no errors found then Python Compiler Converts
into Intermediate Code called BYTE CODE with an extension .pyc (FileName.pyc). If errors found in source
code then we get error displayed on the console.
In EXECUTION PROCESS, The PVM reads the Python Intermediate Code(Byte Code) and Line by Line
and Converted into Machine Under stable Code (Executable or binary Code) and It is read by OS and
Processer and finally Gives Result.
=>Hence In Python Program execution, Compilation Process and Execution Process is taking place Line by
Line conversion and It is one of the Interpretation Based Programming Language.
Example : a=0b1010101010
b=0xBEE
c=0o23
2. High Level Programming Languages:
In these languages, Internally, Even the programmer specifies the data in the form of Low Level
Format such Binary data, Octal Data and Hexa Decimal data, automatically Python Programming Language
Execution Environment Converts into High Level data, which is understandable end-users . Hence Python is
one of the High Level Programming Languages
Examples:
>>> a=0b101010111110000
>>> b=0b10101111000
>>> print(a)-----------------------22000
>>> print(b)----------------------1400
>>> a=0xBEE
>>> print(a)-----------------------3054
>>> bin(22000)-----------------'0b101010111110000'
>>> hex(3054)----------------'0xbee'
7. Robust (Strong):
Definition of Exception: Run time Error (Invalid Input) of every program is called Exception.
8.Extensible:
Extensible feature in Python refers that we can write some of Python Code in Other languages Like
C, CPP, Java, HTML...etc.
It means that it can be extended to other languages and makes other languages programmer easy
in writing and Re-using code of Python and Hence Python Extensible Language.
9. Embedded:
Embedded feature of Python refers, Python Program can also call Other language codes.
For Example:
Inside Python Program, we can use C, C++ and Java Code .
Note: Python is one of the comfortable Programming Language and not a Fastest Programming language.
1) numpy----Numerical calculations
2) pandas---Analysis tool
3) matplotlib-----Data Visualization
4) scipy
5) scikit
Real Time Application developed by Using Python Programming Language:
By Using Python Programming Language, we can develop the following Real Time Applications.
print("Hello, World!")
Hello, World!
Compiler: To translate a program written in a high-level language into a low-level language all at
once, in preparation for later execution.
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
Conditional Control Statements are Executes faster Conditional Control Statements Executes are
slower
Program need not be compiled every time Every time higher level program is
converted into lower level program
Errors are displayed after entire program is checked Errors are displayed for every instruction
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode
1. Interactive mode:
❖ Interactive Mode, as the name suggests, allows us to interact with OS.
❖ When we type Python statement, interpreter displays the result(s) immediately.
Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or explore.
❖ Working in interactive mode is convenient for beginners and for testing small pieces of
code.
Drawback:
❖ We cannot save the statements and have to retype all the statements once
again to re-run them. In interactive mode, you type Python programs and the
interpreter displays the result:
>>> 1 + 1
2
❖ The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for
you to enter code. If you type 1 + 1, the interpreter replies 2.
>>>print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.
2. Script mode:
In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
Scripts can be saved to disk for future use. Python scripts have
the extension .py, meaning that the filename ends with.py
Save the code with filename.py and run the interpreter in script mode to
execute the script.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, we If we are very clear about the code, we can use
can use interactive mode. script mode.
we cannot save the statements for further use and we we can save the statements for further use and we no
have to retype all the statements to re-run them. need to retype all the statements to re-run them.
We can see the results immediately. We can’t see the code immediately.
LINES AND INDENTATION:
In python, lines refer to individual statements or expressions written sequentially in the code. Each line typically
contains one instruction or command that the interpreter executes. These lines can contain:
1. Statements: an operation like an assignment, loop, or function definition.
For example:
x = 5 # this is a statement that assigns the value 5 to x.
print(x) # this statement prints the value of x.
3. Comments: lines that are not executed, used for documentation or to leave notes:
Example:
# this is a comment
4. Blank lines: empty lines used to make the code more readable.
5. Multiline statements: some statements can span multiple lines, using backslashes (`\`) or parentheses:
Example:
total = (1 + 2 +
3 + 4) # a multiline statement using parentheses.
Each line plays a role in forming the logic and flow of a python program.
2. Indentation after Colons: After certain statements (e.g., `if`, `for`, `while`, `def`, and `class`), a colon `:` is used,
followed by an indented block.
Example:
Definition of Variable:
A Variable is one of the Identifier whose can value(s) can be changed during Program execution.
In Programming Language to do any data processing, we must use Variables / Obejcts (Python).
sal=23------valid
$sal=45----Invalid
@name="python"----Invalid
-sal=45-----Invalid
2sal=56----Invalid
456=3.4---Invalid
_sal_=45--valid
_=56---valid
__=5.6--valid
--=45----invalid
3. Within the variable name, No special symbols are allowed except Under Score ( _ )
Examples:
tot sal=45----Invalid
tot_marks=456--valid
tot#sal=56-----NameError
4. No Keywords to be used as Variable Names ( because Keywords are the Reserved Words and
they give special Meaning to the compilers) .
Example:
if=45---------Invalid
else=67---invalid
for=4.5----Invalid
if1=56--Valid
_else=67--valid
_for_=5.6--valid
Note :All Class Name can be used as Variable Names because Class Names are not Keywords
Examples:
>>> age=99----------------Valid
>>> AGE=98---------------Valid
>>> Age=97---------------Valid
>>> aGe=96--------------Valid
>>> print(age,AGE,Age,aGe)----- 99 98 97 96
>>> a=12
>>> A=13
>>> print(a,A)---------- 12 13
Keywords:
These are reserved words and you cannot use them as constant or variable or any other identifier names.
All the Python keywords contain lowercase letters only.
Literals:
A Literal is nothing but a value passing as input to the program.
In Python Programming, Primarily, Literals are classified into 5 types. They are
Python Suite:
In Python, a suite refers to a block of statements grouped together, executed as a unit under a control
structure such as `if`, `for`, `while`, `def`, or `class`. Suites are defined using indentation rather than braces (`{}`)
as in some other programming languages.
if x > 0:
print("Positive") # This is the suite for the `if` block
else:
print("Non-positive") # This is the suite for the `else` block
2. Loops:
Both `for` and `while` loops execute a suite repeatedly, based on the condition.
for i in range(3):
print(i) # Suite for the `for` loop
while x > 0:
print(x)
x -= 1 # Suite for the `while` loop
3.Function Definitions:
A function's body forms a suite that is executed when the function is called.
def greet(name):
print("Hello, " + name) # Suite for the function
4. Class Definitions:
A class definition includes a suite of methods and attributes.
class MyClass:
def __init__(self, name):
self.name = name # Suite for the class method
5.Exception Handling:
Each `try`, `except`, and `finally` block contains a suite of code for handling exceptions.
try:
x=1/0
except ZeroDivisionError:
print("Error: Division by zero") # Suite for `except`
finally:
print("Execution complete") # Suite for `finally`
Suites ensure that related code is grouped and executed together, making Python code structured and readable.
Comments:
Comments can be used to explain Python code. Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Single Line Comments: starts with a #, and Python will ignore the line:
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
print("Hello, World!") #This is a comment
# It can also be used to prevent Python from executing a line of code:
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments:
Python have no syntax for multiline comment so one can use one of two (2) options; insert # for each
line or since Python will ignore string that are not assigned to a variable, you can add a multiline string (""") to
hold your comment
#This is a comment
#written in
#more than just one line
print("Hello, World!")
or
‘’’This is a comment
written in
more than just one line’’’
print("Hello, World!")
Quotations in Python:
', ", ''' or """ are all accepted quotes to denote string in python, as long as the same type of quote starts
and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are allowed:
Example:
word = 'word'
print (word)
sentence = "This is a sentence."
print (sentence)
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
print (paragraph)