0% found this document useful (0 votes)
11 views

PSPP_Unit 1 Notes_25-09-2024.

The document outlines the syllabus for a course on Problem Solving and Programming using Python, covering techniques such as algorithms, flowcharts, and programming methodologies. It discusses problem-solving processes, the qualities of good algorithms, and various programming paradigms including procedural, object-oriented, and functional programming. Additionally, it highlights the importance of software requirements, including operating systems and development tools necessary for programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

PSPP_Unit 1 Notes_25-09-2024.

The document outlines the syllabus for a course on Problem Solving and Programming using Python, covering techniques such as algorithms, flowcharts, and programming methodologies. It discusses problem-solving processes, the qualities of good algorithms, and various programming paradigms including procedural, object-oriented, and functional programming. Additionally, it highlights the importance of software requirements, including operating systems and development tools necessary for programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

PROBLEM SOLVING AND PROGRAMMING USING PYTHON (22CSC40N)

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

● Should be written in simple English


● Each and every instruction should be precise and unambiguous.
● Instructions in an algorithm should not be repeated infinitely.
● Algorithm should conclude after a finite number of steps.
● Should have an end point
● Derived results should be obtained only after the algorithm terminates

Qualities of a good algorithm


The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the time required,
the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The lesser is the
memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of these may
provide more accurate results than others, and such algorithms may be suitable

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

Sequential control flow:


The name suggests the sequential control structure is used to perform the action one after another. Only
one step is executed once. The logic is top to bottom approach.
Example:
Description: To find the sum of two numbers.
1.Start
2.Read the value of ‘a’
3.Read the value of ‘b’
4.Calculate sum=a+b
5.Print the sum of two number
6.Stop

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

Repetition control flow:


Repetition control flow means that one or more steps are performed repeatedly until some condition is reached.
This logic is used for producing loops in program logic when one one more instructions may need to be executed
several times or depending on condition.
Basic Structure:
Repeat until CONDITION is true Statements
Example:
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n
4.1 Print i
5. 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.

Table 1: Flowchart Symbols:

S.No Name of Symbol Type Description


symbol
1. Terminal Symbol Oval Represent the start and stop of
the program.

2. Input/ Output Parallelogram Denotes either input or


symbol output operation.

3. Process symbol Rectangle Denotes the process to be carried

4. Decision symbol Diamond Represents decision making


and branching

5. Flow lines Arrow lines Represents the sequence of steps


and direction of flow. Used to
connect symbols.

6. Connector Circle A connector symbol is


represented by a circle and a
letter or digit is placed in the circle
to specify the link. This symbol is
used to connect flowcharts.
Rules for drawing flowchart:
1. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
2. The flow chart should be clear, neat and easy to follow. There should not be any room for ambiguity in
understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top to bottom.

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.

1. Only one flow line is used in conjunction with terminal 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.

To find nth Fibonacci number:


To display first n natural numbers
To find prime numbers up to
Decision table:
Decision tables are a concise visual representation for specifying which actions to perform depending on given
conditions. They are algorithms whose output is a set of actions.
Why decision table?
 It is a very effective tool used for complex software testing.
 Decision table helps to check all possible combinations of conditions for testing and testers can also
identify missed conditions easily.
 The representation is simple
Disadvantage:
The main disadvantage is that when the number of input increases the table will become more complex.
A simple example of decision table

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.

Conditions Rule 1 Rule 2 Rule 3 Rule 4

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:

def add(a, b):


return a + b

def subtract(a, b):


return a - b

result = add(5, 3)
print(result)

# Output: 8

2. Object-Oriented Programming (OOP):


Organizes code around objects and classes. Objects are instances of classes, which bundle data and behavior
(methods) together.
Use Case: Ideal for large-scale applications where encapsulation, inheritance, and polymorphism are beneficial.
Example:

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:

Sr. Key Bottom-Up Model Top-Down Model


No.
Focus In Bottom-Up Model, the focus is on In Top-down Model, the focus is on
identifying and resolving smallest problems breaking the bigger problem into smaller
1 and then integrating them together to solve one and then repeat the process with
the bigger problem. each problem.

Language Bottom-Up Model is mainly used by object Top-Down Model is followed by


2 oriented programming languages similar to structural programming languages like
Java, C++ etc. C, Fortran etc.
Redundancy Bottom-Up model is better suited as it Top-down model has high ratio of
ensures minimum data redundancy and redundancy as the size of project
3
focus is on re-usability. increases.

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.

Major Functions of Operating System:


● Memory management
● Processor Management
● Device/ hardware management
● Run software applications
● Data management
● Evaluates the system's health
● Provides user interface
● I/O management
● Security
● Time Management
● Deadlock Prevention
● System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consist of programs
that provide performance statistics for the operational staff and security monitors to protect the
system and data.
● System development software includes the language translators that convert programs into
machine language for execution, debugging tools to ensure that the programs are error-free,
and computer-assisted software engineering (CASE) systems.

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

2. Visual Studio Code (VS Code):


Features:
● Lightweight and highly customizable with extensions.
● Integrated terminal and Git.
● Python extension provides IntelliSense, linting, debugging, and code formatting.
● Supports Jupyter notebooks.
Best for: Developers looking for a lightweight editor with extensive customization options.
3. Jupyter Notebook:
Features:
● Interactive coding environment with code, text, and visualizations in one document.
● Ideal for data analysis, machine learning, and education.
● Supports running code in cells.
● Exportable to various formats (e.g., HTML, PDF).
Best for:Data scientists, researchers, and educators.

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.

1. Machine level languages (MLLs)


i) The machine level languages came into existence soon after the advent of computers. These
languages are also called “ first generation languages”
ii) These are the low-level languages directly used by the computer.
iii) The instructions of these languages consists of stings of binary digits 0 and 1.
iv)The general format of the low level instructions is as follows
Opcode Operands

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.

Assembly Level Language Program

Assembler

Equivalent Machine Level Language

3. High-level languages (HLLs)


i) To write complex programs in assembly languages is difficult. So high-level languages
are developed. These are often called third generation languages.
ii) In these programs single statements accomplish, that particular task.
Example:

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.

Creating and Running Programs


Computer hardware understands a program only if it is coded in its machine language.
It is the job of the programmer to write and test the program. There are four steps in this
process: (1) writing and editing the program, (2) compiling the program, (3) linking the program
with the required library modules, and (4) executing the program. These steps are seen in Figure

Assembler, Interpreter, Compiler, Loader, Linker


Assembler:

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:

● Python Programming Language conceived in the year 1980


● Python Programming Language started its Implementation (bring into action) in the year 1989
● Python Programming Language officially released in the year 1991 Feb 20.
● Python Programming Language developed by "GUIDO VAN ROSSUM".
● Python Programming Language Developed at Centrum Wiskude Informatics (CWI) Institute in Nether
lands
● Python Programming Language maintained and Managed by a Non-Commercial Organization called
"Python Software Foundation"(PSF).
● ABC Programming is the predecessor of Python Programming Language
● The official website for Python Software Foundation is www.python.org

Versions of Python Programming :


Python Programming Language contains Three Versions. They are

1) Python 1.x---------- here 1 is called Major Version and here x represents 0 1 2 3 4 5 6 7


(Outdated)
2) Python 2.x----------here 2 is called Major Version and here x represents 0 1 2 3 4 5 6 7
here Python 2.x does not contain Backward compatibility with Python 1.x
Outdated---1 -1 -2020

3) Python 3.x--------here 3 is called Major Version and


here x represents 0 1 2 3 4 5 6 7 8 9 10 11 12 (current Version)

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.

Python Programming Provides the following Features.


1. Simple
2. FreeWare and Open Source
3. Plat Form Independent
4. Dynamically Typed
5. Interpreted
6. High Level Programming
7. Robust (Strong)
8. Extensible
9. Embedded
10. Support Third Part APIs (Modules) Such as numpy, pandas
matplotlib, scipy, scikit, seaborn, nlp keras...etc
1. Simple:
Python of the Simple Programming Language because of 3 Important Technical Features.
They are
1. Python Provide Rich Set of MODULES. So that Python Programmers can RE-USE the
Pre-defined Code and develop the application easily.
Def of MODULE: A Module is a collection of Functions, Variables and Class Names.

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.

2. FreeWare and Open Source:

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

=>Some of the distributions of Python are

1. JPython or Jython----->Used to Run Java Based Applications


2. Iron Python OR Ipython--->Used to C#.net Based Applications.
3. Micro Python----------------->Used to development Micro Controller Applications
4. Anakonda Python------Used to deal with BIG Data / Hadoop Applications.
5. Stackless python------Used to develop Concurrency Applications.
....many more
3. Platform Independent:

● 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

1. Platform Dependent languages.


2. Platform Independent languages.
Platform Dependent languages.
A Language is said to Platform Dependent iff whose data types differs their memory space from One
OS another OS.

Examples: C,CPP...etc

Platform Independent languages:


A Language is said to Platform Independent if whose data types takes Same memory space on All Types
OSes. (Java Slogan)

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)

Example: Java , PYTHON

4. Dynamically Typed:
=>In context Programming, We have Two Types of Programming Languages. They are

1. Static Typed Programming Languages.


2. Dynamically Typed Programming Languages.

1. Static Typed Programming Languages.


=>Data Types are using Explicitly.
=>In Static Typed Programming Languages, It is mandatory to Declare Variables with the help
of Data Types. Without Data Types we can't store and Process Data.

Examples:
int a,b,c; // Variable Declaration
a=10
b=20
c=a+b
Examples: C,C++,JAVA, .NET...etc

2. Dynamically Typed Programming Languages:

=>Data Types are automatically Used by the Python Execution Environment


=>In Dynamically Typed Programming Languages, It is not Necessary to data types for declaration of
Variables. I.e. Python Execution Environment, automatically / Implicitly Assign Data Type based Type of
Value placing in Variable.
Examples:
-------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,type(a))--------------------10 <class 'int'>
>>> print(b,type(b))--------------------20 <class 'int'>
>>> print(c,type(c))--------------------30 <class 'int'>
---------------------
>>> a=10
>>> b=1.2
>>> c=a+b
>>> print(a,type(a))-----------------10 <class 'int'>
>>> print(b,type(b))----------------1.2 <class 'float'>
>>> print(c,type(c))-----------------11.2 <class 'float'>

In Python All Values are stored in the form of OBJECTs.


Behind of Every Object, there is a Class.

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.

Definition of PVM ( Python Virtual Machine)


PVM is one program in Python Software and whose role is to read LINE by LINE of Byte Code and
Converted into Machine Under stable Code (Executable or binary Code)
6. High Level Programming:
In this context, we have two types of languages. They are
1. Low Level Programming Languages
2. High Level Programming Languages

1. Low Level Programming Languages:


In Low Programming Languages, data is always stored in the form low level values such as Binary
data, Octal Data and Hexa Decimal data. These Number System are not directly understandable end-users

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

Python is one of the Robust because of Exception Handling.

Definition of Exception: Run time Error (Invalid Input) of every program is called Exception.

By Default, In every Programming language Exceptions generates Technical Error Messages.

Definition of Exception Handling:-


The Process of Converting Technical Error Messages into User-Friendly Error Messages.

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.

10. Extensive Support for Third Party APIs:


As Python Libraries / API can do many tasks and Operations and unable perform complex
operations and to solve such complex operations more easily and quickly we use Third Party APIs such as

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.

1. Development of Web Applications. (Web Sites)


a) Java Language----Servlets, JDBC, Hibernate,Spring, ...etc(Sun MS)
b) C#.net Language----ASP.net-----(MS)
c) Python Programming----Django, Falsk,Pyramid, Bottle....
2. Development of Gamming Applications.
3. Development of Artificial Intelligence
a)Machine Learning
b) Deep Learning
4. Desktop GUI Applications
5. Image Processing Applications
6. Text Processing
7. Business Application (Apps)
8. Audio and video Based Applications (youtube)
9. Web Scrapping / Harvesting applications.
10.Data Visualization Based Applications.
11. Complex Mathematical Operations
12. Scientific Applications.
13. Software Development.
14. Operating System Installers.
15. CAD and CAM Applications.
16. Embedded Applications
17. Console Based Applications.
18. Language Development.
19. Automation of Testing
20. Animation Applications
21. Data Analysis and Data Analytics
22. Computer Vision.
23. Google Search Engine
.....................Many More

Structure of the Python program:


Python is a high-level, interpreted programming language that is easy to learn and use. It has a simple
and easy-to-understand syntax that emphasizes readability and reduces the cost of program maintenance.
The basic structure of a Python program consists of the following components:
Comments:
Comments are used to explain the purpose of the code or to make notes for other programmers. They
start with a ‘#’ symbol and are ignored by the interpreter.
Import Statements:
Import statements are used to import modules or libraries into the program. These modules contain
predefined functions that can be used to accomplish tasks.
Variables:
Variables are used to store data in memory for later use. In Python, variables do not need to be
declared with a specific type.
Data Types:
Python supports several built-in data types including integers, floats, strings, booleans, and lists.
Operators: Operators are used to perform operations on variables and data. Python supports arithmetic,
comparison, and logical operators.
Control Structures:
Control structures are used to control the flow of a program. Python supports if-else statements, for
loops, and while loops.
Functions:
Functions are used to group a set of related statements together and give them a name. They can be
reused throughout a program.
Classes:
Classes are used to define objects that have specific attributes and methods. They are used to create
more complex data structures and encapsulate code.
Exceptions:
Exceptions are used to handle errors that may occur during the execution of a program.
Overall, the basic structure of a Python program consists of these components working together to accomplish
a specific task or solve a particular problem.

Python Program execution steps:


To execute a Python program in Python's Integrated Development and Learning Environment (IDLE),
follow these steps:

1. Open Python IDLE:


If you have Python installed, you can access IDLE from your start menu or applications menu. Simply search
for "IDLE" and click on it.

2. Create a New Python File:


Once IDLE is open, create a new file by selecting:
- File → New File (or press `Ctrl + N`).

3. Write Your Python Code:


In the new file window, you can write your Python code. For example, let's write a simple script:

print("Hello, World!")

4. Save the File:


Save your file by selecting:
File → Save (or press `Ctrl + S`).
Choose a location and a filename with a `.py` extension, e.g., `hello.py`.

5. Run the Program:


After saving your file, you can run your program by selecting:
Run → Run Module (or press `F5`).
- The output will be displayed in the Python shell (IDLE window). For the above example, you should see:

Hello, World!

6. Exit or Continue Programming:


You can continue editing your code, save changes, and run the program again by pressing `F5`.
When you're done, you can close IDLE by selecting File → Exit.
These are the basic steps to write, save, and run a Python program in IDLE.
PYTHON INTERPRETER AND SCRIPT MODE OF PROGRAMMING:
Python interpreter:

Interpreter: To execute a program in a high-level language by translating it one line at a time.

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

Intermediate Object Code is Generated No Intermediate is Object Code Generated

Conditional Control Statements are Executes faster Conditional Control Statements Executes are
slower

Memory Requirement is More(Since Object Code is Memory Requirement is Less


Generated)

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

interpreted (if any)

Example : C Compiler Example : PYTHON

Modes of python interpreter:

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.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to read and
typing commands and expressions at the prompt. execute statements in a 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.

2. Expressions: an operation that evaluates to a value, like mathematical operations:


Example:
y = 2 + 3 # an expression where 2 and 3 are added, and the result is assigned to y.

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.

WHAT IS INDENTATION IN PYTHON?


Indentation in Python refers to the spaces or tabs used at the beginning of a line to define the structure
and hierarchy of the code. Unlike many other programming languages that use braces `{}` to group code blocks,
Python uses indentation to indicate blocks of code that belong together, such as those inside loops, functions,
and conditionals.

Why Indentation Matters


● Python enforces strict indentation, meaning the level of indentation determines which code is part of
which block.
● Improper indentation will lead to syntax errors, or the program may behave unexpectedly.

What are Indentation Rules?


1. Consistent Indentation: All lines of code within the same block must be indented by the same amount.
Typically, 4 spaces are used per level of indentation.
Example:

if x > 0: # Indented by 4 spaces


print("Positive number") # Same indentation level, part of the `if` block
else:
print("Non-positive number") # Same indentation level, part of the `else` block

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:

def my_function(): # Colon followed by an indented block


print("Hello, world!") # This line is indented
```
3. Syntax Errors from Incorrect Indentation: If the indentation is not consistent or is missing, Python will raise
an error.
Example:
if x > 0:
print("This will cause an Indentation Error") # This line is not indented

Common Indentation Errors:


Indentation Error: Raised when there's an incorrect level of indentation.
Mixed Tabs and Spaces: Mixing tabs and spaces in Python will result in an error. It's recommended to use only
spaces (commonly 4 spaces) to avoid issues.
Indentation in Python is critical for defining code blocks and ensuring the code runs as expected.

Identifiers or Variables and keywords:


We know that all types of Literals are stored in main memory by allocating Sufficient amount of Memory
with help of Data Types. To Process the Data / Literals stored in main memory, we must give distinct names to
the created memory space and these distinct names makes us to identify the values and they are also called
IDENTIFIERS.
During Program Execution IDENTIFIER Values can be changed / Varying and hence IDENTIFIERs are called
VARIABLES. Hence All Types of LITERALS must be stored in the form of VARIABLES. In Python Programming All
Variables are called Objects.

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

Rules for Using Variables or Identifiers in Python Program


To Use Variables in Python Programming, We use the following Rules.
1. A Variable Name is a combination of Alphabets, Digits and a Special Symbol Under Score( _ ).
2. First Letter of the Variable Names must starts Either with Alphabet or Special Symbol Under
Score ( _ )
Examples:

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

5. All Variable Name are Case Sensitive

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

1. Integer Literals------Example---> 234 567 23


2. String Literals--------Examples--->"Python", "Rossum", "Ram"
3. Float Literals---------Examples----> 34.56 4.5 99.99 0.999
4. Boolean Literals-----Examples-----> True False
5. Date Literals-----------Examples:----> 29-08-2022, 17-08-2022...etc

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.

How Python Suites Work


Indentation: A suite is defined by consistent indentation (typically 4 spaces). All the statements that belong to
the same block must have the same indentation.
Single-line Suites: Python allows a suite to be written on a single line for simple cases.
Example Structures Using Suites:
1. Conditional Statements:
An `if`, `elif`, or `else` block contains a suite of indented code that is executed when the condition is met.

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`

Single-line Suite Example


For simple cases, Python allows a single-line suite:
if x > 10: print("x is greater than 10")
Key Points:
● Suites are used in control structures to group related statements.
● Proper indentation is required to define suites in Python.
● Inconsistent indentation or misuse of indentation will lead to `IndentationError`.

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)

You might also like