pgdca_103_Python
pgdca_103_Python
IHRD AC
PGDCA103:
Programming with Python
F IRST E DITION
IHRD
P REFACE
Welcome to PGDCA103 - Programming with Python, a comprehensive handbook designed for students
enrolled in the Post Graduate Diploma in Computer Applications (PGDCA) program. This handbook aims
to equip you with the fundamental and advanced concepts of Python programming, a language renowned
for its simplicity, readability, and versatility.
In an era where technology pervades every aspect of our lives, Python stands out as one of the most
influential programming languages. Its application spans various domains including web development,
data analysis, artificial intelligence, machine learning, and more. Python’s user-friendly syntax makes it
an ideal choice for beginners, while its robust libraries and frameworks cater to the needs of experienced
developers.
The primary objective of PGDCA103 is to provide you with a solid foundation in Python programming.
By the end of this course, you will be proficient in writing Python code, solving complex problems, and
developing real-world applications. This handbook is structured to facilitate your learning through a
systematic approach, starting from the basics and gradually progressing to more complex topics.
— IHRD AC
2024-06-05
I
C ONTENTS
I Module 1 1
1 Module -1 3
1.1 Basic Model of Computation . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Finite Automata . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Turing Machine. . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3.1 Characteristics of Algorithms . . . . . . . . . . . . . . . . . 5
1.1.4 Pseudo Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.1.5 Flow Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Programming paradigms . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.1 Subroutines & Blocks . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.1.1 Subroutines . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.1.2 Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.2 Differences and Relationships . . . . . . . . . . . . . . . . . . . . 8
1.2.3 Practical Usage . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3 Syntax & Semantics. . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.2 Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Program Development Life Cycle (PDLC) . . . . . . . . . . . . . . . . . . 10
1.4.1 Summary of PDLC Stages . . . . . . . . . . . . . . . . . . . . . 12
1.4.2 Importance of PDLC. . . . . . . . . . . . . . . . . . . . . . . . 12
1.4.3 Concept of Bugs Classification, Errors, Exceptions. . . . . . . . . . . . 12
1.4.4 Evolution of Programming Languages . . . . . . . . . . . . . . . . . 14
1.4.4.1 Early Programming Languages . . . . . . . . . . . . . . . . 14
1.4.4.2 High-Level Languages . . . . . . . . . . . . . . . . . . . 14
1.4.4.3 The Advent of Structured Programming. . . . . . . . . . . . . 14
1.4.4.4 Object-Oriented Programming (OOP) . . . . . . . . . . . . . 14
1.4.4.5 Modern and Scripting Languages . . . . . . . . . . . . . . . 14
1.4.4.6 Contemporary Languages . . . . . . . . . . . . . . . . . . 15
1.4.5 Evolution of Compilers. . . . . . . . . . . . . . . . . . . . . . . 15
1.4.5.1 Early Compilers . . . . . . . . . . . . . . . . . . . . . . 15
1.4.5.2 Intermediate Representations . . . . . . . . . . . . . . . . . 15
1.4.5.3 Just-In-Time Compilation . . . . . . . . . . . . . . . . . . 15
1.4.5.4 Modern Compiler Developments . . . . . . . . . . . . . . . 15
III
IV CONTENTS
II Module 2 20
2 Module -2 22
2.1 Python Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.1 Features of Python . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.2 History and Versions. . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.3 Applications of Python . . . . . . . . . . . . . . . . . . . . . . . 23
2.1.4 Working in Console and Python Shell . . . . . . . . . . . . . . . . . 23
2.2 Basic Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1
PART I
M ODULE 1
Basic model of computation, Notion of Algorithms, Pseudo code, Flow chart.
Programming paradigms – Structured, Functional, Object Oriented, Structured
Program Theorem: Sequence, Selection, Iteration, Subroutines, Blocks. Definition
of Syntax and Semantics.
Program Development Life Cycle (PDLC) - analysing, designing, coding, debug-
ging, and testing, and documenting, implementing, and maintaining. Concept of
Bugs – Classification, Errors, Exceptions. Evolution of Programming Languages,
Compilers, and Interpreters. Cross compiling, Concept of TDD.
1 M ODULE -1
Part I
Note 1.1.1.
A finite state automaton is a mathematical object with five conponents, M = (Q, Σ, δ , q0, F), where.
Q is a finite set of states. Σ is a finite set of input symbols. δ : Q×Σ → Q is a total function (called
the transition function) q0∈ Σ is the start state.
3
4 1.1. BASIC MODEL OF COMPUTATION
• Deterministic Finite Automaton (DFA): A model where for each state and input symbol, there is
1 exactly one transition to a new state.
• Nondeterministic Finite Automaton (NFA): A model where for each state and input symbol, there
PGDCA103: PROGRAMMING WITH PYTHON
• Transition Function: Defines state transitions based on the current state and input symbol
• Accept States: A set of states that define when the input string is accepted.
Operation:
A finite automaton processes an input string symbol by symbol, transitioning between states according
to the transition function. A string is accepted if, after processing all symbols, the automaton is in an
accept state.
• Tape: An infinite sequence of cells that can hold symbols from a finite alphabet.
• Head: A device that can read and write symbols on the tape and move left or right.
• State Register: Holds the current state of the Turing machine, chosen from a finite set of states.
• Transition Function: Describes the machine’s actions based on the current state and the symbol it
reads. It dictates the next state, the symbol to write, and the head’s movement direction.
Operation:
The Turing machine starts in an initial state with the head positioned over the first cell of the tape. It
follows the transition function to read the current symbol, write a new symbol (if necessary), move the
head, and change its state. This process continues until the machine reaches a halt state or runs indefinitely.
The Turing machine model is significant because it captures the essence of algorithmic computation.
If a problem can be solved by a Turing machine, it is considered computable. Turing machines help define
the limits of what can be computed and form the basis for complexity theory and the study of decidability.
1.1.3 Algorithms
An algorithm is a finite, well-defined sequence of computational steps that solves a problem or performs
a task. Algorithms are expressed in a way that they can be implemented in a programming language and
executed by a computer.
1.1. BASIC MODEL OF COMPUTATION 5
MODULE -1
• Definiteness: Each step of the algorithm must be precisely defined.
• Effectiveness: Each step must be basic enough to be performed exactly in a finite amount of time.
Algorithms are the core of computer science, forming the basis for all software. They are used to solve
problems in various domains such as sorting, searching, optimization, and cryptography. The study of
algorithms includes their design, analysis, and optimization to ensure they are efficient and scalable.
The basic model of computation, encompassing Turing machines, finite automata, and algorithms,
provides a fundamental understanding of how problems are solved using computational methods. These
models help us define the limits of computation, analyze the efficiency of algorithms, and design effective
solutions for a wide range of problems. As the field of computer science evolves, these foundational
concepts continue to play a crucial role in advancing technology and solving complex challenges.
• Readable: Designed to be easily read and understood by humans, regardless of their programming
knowledge.
• Informal: Not meant to be executed by a computer but to convey the logic of the program.
1 Algorithm FindMaximum
2 Input: List of numbers
3 Output: Maximum number in the list
4
5 1. Initialize max to the first element of the list
6 2. For each number in the list
7 a. If the number is greater than max
8 i. Set max to the number
9 3. Return max
10
11
6 1.2. PROGRAMMING PARADIGMS
1. Oval: Start/End
2. Rectangle: Process
3. Diamond: Decision
4. Parallelogram: Input/Output
MODULE -1
Note 1.2.2.
Structured Program Theorem
This theorem states that any computable function can be computed using only three control structures:
sequence, selection, and iteration.
1.2.1.1 Subroutines
Subroutines, also known as functions, procedures, or methods (depending on the programming
language), are blocks of code designed to perform a specific task. They are reusable pieces of code that
can be called from multiple places within a program. Subroutines help in modularizing code, making it
more readable, maintainable, and reusable.
Key Characteristics of Subroutines:
1.2.1.2 Blocks
Blocks are sections of code that are grouped together. They are defined by indentation or specific
keywords depending on the programming language. Blocks can contain multiple statements and are used
to control the flow of execution, such as within loops, conditional statements, and subroutines.
Key Characteristics of Blocks:
• Control Flow: They control the flow of execution (e.g., if, for, while blocks).
Example:
1 x = 10
2 if x > 5:
3 print("x is greater than 5")
4 y = x * 2
5 print("Value of y:", y) # Output: "x is greater than 5" and "Value
of y: 20"
6
7
• Functionality: Subroutines encapsulate functionality that can be reused, while blocks are used to
control the flow of execution within the program.
• Reusability: Subroutines can be called multiple times from different parts of a program, but blocks
are executed as part of the surrounding code structure.
1.3. SYNTAX & SEMANTICS 9
MODULE -1
• Blocks are used to implement control structures like loops (for, while), conditionals (if, else), and to
define the body of subroutines.
Example:
1
2 def process_numbers(numbers):
3 total = 0
4 for number in numbers: # ’for’ block
5 if number > 0: # ’if’ block within ’for’ block
6 total += number
7 return total # End of function block
8
9 nums = [1, -2, 3, 4, -5]
10 result = process_numbers(nums)
11 print(result) # Output: 8
12
13
In the context of programming languages, syntax and semantics are two fundamental concepts that
define how programs are written and how they behave.
1.3.1 Syntax
Syntax refers to the set of rules that define the structure and form of valid statements in a programming
language. It specifies how symbols, keywords, and punctuation must be arranged to create correctly
formatted programs. Syntax rules are similar to grammar rules in natural languages.
Key Points about Syntax:
1.3.2 Semantics
Semantics refers to the meaning or behavior of the syntactically correct statements in a programming
language. It defines what the statements do when they are executed, i.e., the effect of the code on the
program’s state or the actions performed by the code.
Key Points about Semantics:
10 1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)
• Meaning: Focuses on what the code does, rather than how it looks.
1 • Behavior: Defines the effect of the code on the state of the program or the output produced.
• Execution: Concerned with the execution of the code and the resulting actions.
PGDCA103: PROGRAMMING WITH PYTHON
he Program Development Life Cycle (PDLC) is a systematic process used by software developers and
engineers to plan, design, develop, test, and maintain software applications. It is analogous to the Software
Development Life Cycle (SDLC) but focuses more on the programming and development aspect.
Stages in PDLC are:
1. Problem Definition
This initial stage involves understanding and defining the problem that the software needs to solve.
It includes gathering requirements, identifying the objectives, and understanding the constraints.
Key Activities:
2. Program Design
In this stage, developers create a detailed plan for the solution, including the overall architecture and
specific algorithms. It involves creating both high-level and low-level designs.
Key Activities:
3. Coding (Implementation)
During the coding phase, developers translate the design documents into actual source code using a
programming language. This is where the main development work occurs.
Key Activities:
4. Testing
Testing is a critical phase where the developed software is tested to find and fix bugs and ensure it
meets the specified requirements. This stage ensures the quality and functionality of the software.
1
MODULE -1
Key Activities:
• Conducting unit testing, integration testing, system testing, and acceptance testing
• Identifying and fixing bugs Verifying that the software meets the requirements
5. Debugging
Debugging involves identifying, isolating, and fixing bugs or defects in the code. It is often an
iterative process where developers continuously test and refine the software.
Key Activities:
6. Documentation
Documentation is crucial for maintaining and updating the software in the future. It includes both
user documentation and technical documentation for developers.
Key Activities:
7. Maintenance
Maintenance involves making updates, enhancements, and corrections to the software after it has
been deployed. This phase ensures the software remains functional and relevant over time.
Key Activities:
By following the PDLC, software development teams can create robust, efficient, and maintainable
software solutions that meet user requirements and stand the test of time.
1. Based on Severity
• Critical Bugs: These bugs cause complete failure or crash of the system, leading to a total
inability to use the software. They require immediate attention.
• Major Bugs: These bugs severely affect the functionality, making it difficult to use the software,
but the system is still operable.
• Minor Bugs: These bugs cause small issues that do not significantly affect the software’s
functionality. They are often related to user experience or cosmetic issues.
• Trivial Bugs: These are insignificant issues that have no real impact on the system’s functional-
ity. They might include things like minor typos or slight visual misalignments.
2. Based on Nature
• Functional Bugs: These occur when the software does not behave as expected in terms of
functionality. For example, a button does not trigger the intended action.
• Performance Bugs: These are related to the speed, responsiveness, or resource usage of the
software. For example, the software might run slower than expected.
1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC) 13
• Security Bugs: These are vulnerabilities that can be exploited by attackers to gain unauthorized
access or perform malicious actions.
• Usability Bugs: These affect the user experience, such as confusing interfaces or difficult-to-use
1
features.
MODULE -1
• Compatibility Bugs: These occur when the software does not work as expected on different
environments, such as different operating systems, browsers, or hardware.
3. Based on Priority
• High-Priority Bugs: These must be fixed immediately because they are blocking important
functionality or critical processes.
• Medium-Priority Bugs: These need to be addressed, but they can wait until higher-priority
bugs are resolved.
• Low-Priority Bugs: These are not urgent and can be fixed at a later stage. They might include
enhancements or minor issues.
4. Based on Reproducibility
• Consistent Bugs: These bugs can be reproduced every time under the same conditions.
• Intermittent Bugs: These occur sporadically and are difficult to reproduce, making them harder
to fix.
• Heisenbugs: These bugs disappear or change behavior when an attempt is made to study them,
often due to timing issues or race conditions.
5. Based on Origin
• Coding Bugs: These arise due to mistakes made during the coding process, such as syntax
errors or logic flaws.
• Design Bugs: These are introduced during the design phase and might involve incorrect
workflows or poorly thought-out architecture.
• Integration Bugs: These occur when different modules or systems interact, leading to unex-
pected behavior.
• Configuration Bugs: These arise from incorrect settings or environment configurations.
6. Based on Detection Phase
• Unit Testing Bugs: Found during the unit testing phase when individual components are tested.
• Integration Testing Bugs: Detected during the integration testing phase when combined
components are tested together.
• System Testing Bugs: Found during system testing when the entire system is tested as a whole.
• User Acceptance Testing (UAT) Bugs: Discovered during the final testing phase by the
end-users or clients.
Understanding the classification of bugs is essential for prioritizing their resolution and ensuring the
stability and reliability of software products. In short the following can be said about bugs and errors:
• Bugs: Flaws in software that cause incorrect or unintended behavior.
• Errors: Issues in the code that prevent it from running correctly, such as syntax errors or logic errors.
• Exceptions: Runtime anomalies or unusual conditions that disrupt normal flow, often handled using
try/catch mechanisms.
14 1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)
MODULE -1
safety, performance, and modern programming features.
Rust (2010): Developed by Mozilla, Rust focuses on safety and performance, particularly in system-
level programming, by avoiding common programming errors like null pointer dereferencing and data
races.
Kotlin (2011): Developed by JetBrains, Kotlin is fully interoperable with Java and has become the
preferred language for Android development.
Cross-compiling is the process of building executable code for a platform different from the one
on which the compiler is running. This technique is essential when developing software for embedded
systems, mobile devices, or other environments where it’s not practical or possible to compile code directly
on the target device.
2. Target System: The machine or platform for which the compiled code is intended. The architecture,
operating system, or both may differ from the host system.
3. Cross-Compiler: A compiler that runs on the host system but generates executable code for the target
system. For example, a cross-compiler running on a Windows machine might produce binaries for
an ARM-based Linux device.
1.5. CROSS COMPILING 17
4. Toolchain: A set of programming tools used in the process of software development, including the
cross-compiler, linker, libraries, and other utilities needed to build software for the target system. 1
5. Linker: The tool that combines various compiled object files into a single executable or library
MODULE -1
that runs on the target system. The linker must understand the format and architecture of the target
system.
• Different Architectures: The host and target systems may have different CPU architectures (e.g.,
compiling on x86 for ARM), requiring specialized compilers and linkers to generate compatible
binaries.
• Development Speed: Cross-compiling can speed up the development process by allowing developers
to compile and test code on more powerful machines before deploying it to resource-constrained
target devices.
• Automation and CI/CD: Cross-compiling is often used in automated build environments where code
needs to be compiled for multiple platforms from a single codebase.
• Operating Systems: Building operating systems, like Linux distributions, often involves cross-
compiling to create binaries for various target architectures (e.g., ARM, x86, PowerPC).
• Configuration: Properly configuring the build system to use the correct cross-compiler and link
against the right libraries for the target platform can be tricky.
• Testing: Testing cross-compiled code can be challenging, especially when the target hardware is not
readily available. Emulators and virtual machines are often used to test cross-compiled binaries.
• Clang/LLVM: Clang, part of the LLVM project, also supports cross-compilation and is known for
its modularity and flexibility.
18 1.6. CONCEPT OF TDD
• CMake: A popular build system that can be configured to cross-compile projects by specifying the
1 target architecture and toolchain.
systems and applications targeting diverse platforms. Despite its challenges, mastering cross-compiling
can greatly enhance development efficiency and enable the creation of software for a wide range of
environments.
Test-Driven Development (TDD) is a software development approach where tests are written before
the actual code. It’s a process that emphasizes writing small, automated tests that define the expected
behavior of a feature before implementing the feature itself. TDD helps ensure that the code meets its
requirements, improves code quality, and simplifies maintenance.
Key Concepts of TDD are:
1. Red-Green-Refactor Cycle:
• Red: Write a test for a new feature or functionality. Since the feature isn’t implemented yet,
the test should fail. This failure indicates that the feature is not yet complete.
• Green: Write the minimal amount of code needed to make the test pass. The goal is to quickly
implement the feature so that the test passes.
• Refactor: Once the test passes, improve the code by refactoring it. Refactoring involves
cleaning up the code, improving its structure, and removing duplication without changing its
behavior. The test ensures that the feature still works after refactoring.
2. Write Tests First: In TDD, you write the test cases before writing the code. This ensures that you
have a clear understanding of the feature’s requirements and how it should behave.
3. Small, Incremental Steps: TDD encourages making small, incremental changes to the code. Each
test corresponds to a small piece of functionality, allowing developers to focus on one aspect of the
problem at a time.
4. Automated Testing: he tests written in TDD are automated, meaning they can be run repeatedly
without manual intervention. Automated tests provide quick feedback and help catch regressions
when the code is modified.
5. Refactoring: Refactoring is a crucial part of TDD. After making the test pass, developers are
encouraged to refactor the code to improve its design, make it more maintainable, and remove any
inefficiencies.
6. Test Coverage: TDD naturally leads to high test coverage since every piece of functionality is tested.
High test coverage increases confidence in the code and reduces the likelihood of bugs.
• Documentation: Tests act as documentation for the code, clearly showing what each piece of
functionality is supposed to do. 1
• Confidence in Refactoring: Since tests are in place, developers can refactor the code with confidence,
MODULE -1
knowing that if they break something, the tests will catch it.
• Focus on Requirements: TDD ensures that developers focus on the requirements and functionality
of the code, as tests are written based on the expected behavior.
• Time-Consuming: Writing tests first can initially slow down development, although this is often
offset by the time saved in debugging and maintenance.
• Overhead for Simple Projects: In very simple projects or prototypes, the overhead of writing tests
first may seem unnecessary
• Requires Discipline: TDD requires discipline to consistently write tests first and resist the urge to
jump straight into coding.
TDD is a powerful methodology that emphasizes writing tests before code, leading to higher code
quality, better design, and fewer bugs. While it requires discipline and can be challenging to adopt initially,
the long-term benefits in terms of code maintainability, reliability, and developer confidence often make it
a worthwhile investment.
20
PART II
M ODULE 2
Description of various python distributions (CPython, Anaconda, Ac-
tivePython, Jython) – Installations, Features of Python, History and Versions, Ap-
plications of Python, Working in Console and Python Shell, Basic Syntax, Variables,
Keywords and Comments, Numbers and Strings, Booleans, Operators, converting
data types, Control statements: if, if-else, nested if, for loop, while loop, break and
continue, pass, match – case, try – except. Generic Data types, list, tuple, dict,
set, list comprehension, slicing, sorting of list, dict and tuple, sorted(), reversed().
Input/output functions – formatted strings – string methods, Modules and user
defined functions, Iterators, Generators, magic/ dunder methods, creating user
defined modules, doc string. Functions from Built-in Modules, built-in functions,
mathematical functions, date time functions, random numbers, writing user-defined
functions, the composition of functions, parameters, and arguments, default param-
eters, function calls, return statements, using global variables, recursion lambda
function. Constructing Modules and Packages.
M ODULE -2
2
Part II
1. CPython Description: The default and most widely used implementation of Python, written in
C. Features: Highly compatible with Python standards, extensive standard library, wide range of
third-party modules. Installation: Download from python.org.
2. Anaconda Description: A distribution focused on data science and machine learning, including
numerous pre-installed packages. Features: Conda package manager, Jupyter Notebook, Spyder
IDE, pre-installed libraries for data analysis (numpy, pandas, etc.). Installation: Download from
anaconda.com.
4. Jython Description: An implementation of Python that runs on the Java platform. Features: Allows
the use of Java libraries in Python, integration with Java applications. Installation: Download from
jython.org.
2. Interpreted Language: No need to compile code before execution, which simplifies the development
process.
• Major Versions: Python 2.x: Introduced many foundational features. Python 3.x: Released in
2008, not backward compatible with Python 2.x but includes many improvements and new features.
Current Version: Python 3.11 (as of 2024).
22
2.2. BASIC SYNTAX 23
MODULE -2
3. Scripting: Automating tasks, writing scripts.
4. Scientific Computing: Libraries like SciPy.
5. Finance: Quantitative analysis, algorithmic trading.
6. Game Development: Libraries like Pygame.
7. Artificial Intelligence: PyTorch, TensorFlow.
Apart from these, as python is widely being used in all walks of software development today.
2. Keywords and Comments: Reserved words for specific purposes, comments for code explanation.
1 # This is a comment
2 for i in range(5):
3 print(i)
4
5
4. Booleans
2 1
2
is_active = True
is_closed = False
3
PGDCA103: PROGRAMMING WITH PYTHON
5. Operators
4. https://onlinecourses.nptel.ac.in/noc23_cs20/preview
IHRD H ANDBOOKS
IHRD