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

pgdca_103_Python

The PGDCA103 handbook on Programming with Python is designed for students in the Post Graduate Diploma in Computer Applications program, focusing on both fundamental and advanced concepts of Python. It covers various programming paradigms, the program development life cycle, and the evolution of programming languages, compilers, and interpreters. By the end of the course, students will be proficient in writing Python code and developing real-world applications.

Uploaded by

Dileep Kumar K
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)
36 views

pgdca_103_Python

The PGDCA103 handbook on Programming with Python is designed for students in the Post Graduate Diploma in Computer Applications program, focusing on both fundamental and advanced concepts of Python. It covers various programming paradigms, the program development life cycle, and the evolution of programming languages, compilers, and interpreters. By the end of the course, students will be proficient in writing Python code and developing real-world applications.

Uploaded by

Dileep Kumar K
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/ 33

IHRD H ANDBOOKS

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

1.4.6 Evolution of Interpreters . . . . . . . . . . . . . . . . . . . . . . 15


1.4.6.1 Early Interpreters. . . . . . . . . . . . . . . . . . . . . . 15
1.4.6.2 Scripting Languages . . . . . . . . . . . . . . . . . . . . 16
1.4.6.3 Bytecode Interpreters . . . . . . . . . . . . . . . . . . . . 16
PGDCA103: PROGRAMMING WITH PYTHON

1.4.6.4 Just-In-Time (JIT) Interpreters . . . . . . . . . . . . . . . . 16


1.4.6.5 Modern Interpreter Trends . . . . . . . . . . . . . . . . . . 16
1.5 Cross Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5.1 Key Concepts of Cross-Compiling . . . . . . . . . . . . . . . . . . 16
1.5.2 Why Cross-Compiling is Necessary. . . . . . . . . . . . . . . . . . 17
1.5.3 Examples of Cross-Compiling . . . . . . . . . . . . . . . . . . . . 17
1.5.4 Challenges of Cross-Compiling . . . . . . . . . . . . . . . . . . . 17
1.5.5 Toolchains for Cross-Compiling . . . . . . . . . . . . . . . . . . . 17
1.6 Concept of TDD . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.6.1 Advantages of TDD . . . . . . . . . . . . . . . . . . . . . . . . 18
1.6.2 Challenges of TDD . . . . . . . . . . . . . . . . . . . . . . . . 19

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

Sec 1.1 Basic Model of Computation

Computation is the process of performing a sequence of operations to solve a problem or achieve


a particular result. A model of computation provides a formal framework to describe the execution of
algorithms. Understanding these models is crucial as they form the foundation of computer science,
enabling us to analyze and design efficient algorithms. This section introduces the basic model of
computation, focusing on the Turing machine, finite automata, and the concept of algorithms.

1.1.1 Finite Automata


Finite automata are abstract machines that recognize patterns within input taken from some character
set. They have a finite number of states and transition between these states based on input symbols.
Finite automata can be represented by input tape and finite control.
• Input tape: It is a linear tape having some number of cells. Each input symbol is placed in each cell.
• Finite control: The finite control decides the next state on receiving particular input from input tape.

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.

Types of Finite Automata:

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

can be multiple possible transitions.

Components of a Finite Automaton:

• States: A finite set of states.

• Alphabet: A finite set of symbols.

• Transition Function: Defines state transitions based on the current state and input symbol

• Start State: The state where the automaton begins.

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

1.1.2 Turing Machine


The Turing machine, introduced by Alan Turing in 1936, is one of the most fundamental models of
computation. It provides a simple yet powerful framework to understand what can be computed and how.
Components of a Turing Machine:

• 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

1.1.3.1 Characteristics of Algorithms

• Finiteness: An algorithm must terminate after a finite number of steps. 1

MODULE -1
• Definiteness: Each step of the algorithm must be precisely defined.

• Input: An algorithm has zero or more inputs.

• Output: An algorithm produces one or more outputs.

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

1.1.4 Pseudo Code


Pseudo code is a high-level description of an algorithm or program written in a form that resembles
programming language syntax but is meant to be easily understood by humans. It is not bound by the
strict syntax rules of programming languages and often uses plain English to describe the steps.
Characteristics of Pseudo Code:

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

• Language-Agnostic: Can be translated into any programming language.

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.1.5 Flow Chart


1 A flow chart is a graphical representation of an algorithm or a process. It uses various symbols to
denote different types of actions or steps in a process. Common symbols include:
PGDCA103: PROGRAMMING WITH PYTHON

1. Oval: Start/End

2. Rectangle: Process

3. Diamond: Decision

4. Parallelogram: Input/Output

5. Flow Lines (Arrows): Show the direction of the process flow.

Sec 1.2 Programming paradigms

A programming paradigm is a fundamental style of computer programming, providing a way to


structure and organize code. Different paradigms offer different tools, techniques, and methodologies for
solving problems and writing software. Understanding various paradigms is crucial for selecting the right
approach for a given task and for becoming a versatile programmer.
1.2. PROGRAMMING PARADIGMS 7

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. Sequence: Executing statements one after another.

2. Selection: Making decisions (if/else).

3. Iteration: Looping (for, while).

1.2.1 Subroutines & Blocks


In programming, subroutines and blocks are fundamental concepts that help in organizing and manag-
ing code.

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:

• Encapsulation: Subroutines encapsulate a specific task or functionality.

• Parameters: They can accept input values called parameters or arguments.

• Return Values: Subroutines can return a value after execution.

• Reusability: They allow code to be reused without duplication.


8 1.2. PROGRAMMING PARADIGMS

• Abstraction: They provide a level of abstraction by hiding the implementation details.


1 Example:
PGDCA103: PROGRAMMING WITH PYTHON

1 def add(a, b):


2 return a + b
3
4 result = add(5, 3) # Calling the subroutine
5 print(result) # Output: 8
6
7

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:

• Grouping Statements: Blocks group multiple statements together.

• Control Flow: They control the flow of execution (e.g., if, for, while blocks).

• Scope: Blocks define the scope of variables and subroutines.

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

1.2.2 Differences and Relationships


• Scope: Subroutines have their own scope for variables defined within them, whereas blocks may or
may not define a new scope depending on the language.

• 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

1.2.3 Practical Usage


• Subroutines are used to break down complex problems into manageable pieces, encapsulating
specific functionality like calculating a result, processing data, or handling an event.
1

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

Sec 1.3 Syntax & Semantics

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:

• Structure: Defines the correct arrangement of symbols and keywords.


• Rules: Includes rules for combining identifiers, operators, delimiters, and other language constructs.
• Parsing: Syntax is concerned with how the code is parsed or interpreted by the compiler or interpreter.

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

Sec 1.4 Program Development Life Cycle (PDLC)

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:

• Requirement gathering from stakeholders


• Defining the scope of the problem
• Documenting the problem statement and objectives

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:

• Designing algorithms and data structures


• Creating flowcharts or pseudocode
• Defining the architecture and modules
• Planning user interfaces (if applicable)

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:

• Writing code based on the design specifications


• Adhering to coding standards and guidelines
• Implementing error handling and input validation
• Creating unit tests alongside the code
1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC) 11

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:

• Using debugging tools to trace and resolve issues


• Reviewing code to find logical errors
• Re-running tests to ensure issues are resolved

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:

• Writing user manuals and help guides


• Documenting code and design decisions
• Creating API documentation (if applicable)

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:

• Implementing software updates and patches


• Enhancing features and adding new functionalities
• Monitoring performance and fixing any new issues that arise
• Providing technical support to users
12 1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)

1.4.1 Summary of PDLC Stages


1 • Problem Definition: Understanding and defining the problem.

• Program Design: Planning the solution architecture and design.


PGDCA103: PROGRAMMING WITH PYTHON

• Coding (Implementation): Writing the actual source code.

• Testing: Verifying the software works correctly.

• Debugging: Identifying and fixing defects.

• Documentation: Creating user and technical documentation.

• Maintenance: Updating and maintaining the software.

1.4.2 Importance of PDLC


• Structure: Provides a structured approach to software development, ensuring all aspects are covered.

• Quality: Ensures high-quality software through systematic testing and debugging.

• Maintainability: Facilitates easier maintenance and updates through thorough documentation.

• Efficiency: Improves development efficiency by defining clear stages and 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.4.3 Concept of Bugs Classification, Errors, Exceptions


Bugs in software development refer to flaws, errors, or faults in a program that produce unintended or
incorrect results. Bugs can be classified based on various criteria, including their severity, nature, origin,
and impact. Here’s a breakdown of the common classifications:

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)

1.4.4 Evolution of Programming Languages


1 The evolution of programming languages, compilers, and interpreters is a fascinating journey that
reflects the changing needs of technology, computation, and human interaction with machines.
PGDCA103: PROGRAMMING WITH PYTHON

1.4.4.1 Early Programming Languages


Machine Language (1940s): The earliest form of programming languages, consisting of binary code
(0s and 1s) that the computer’s hardware could execute directly. Programming in machine language was
extremely tedious and error-prone.
Assembly Language (1950s): To make programming easier, assembly language was developed. It
uses mnemonic codes or symbols to represent machine-level instructions. Assemblers are used to translate
assembly code into machine code.

1.4.4.2 High-Level Languages


FORTRAN (1957): The first high-level programming language designed for scientific and engineering
calculations. It introduced the concept of abstraction, allowing developers to write instructions in a more
human-readable form.
COBOL (1959): Designed for business data processing, COBOL (Common Business-Oriented
Language) introduced more readability with English-like syntax, focusing on business applications.
LISP (1958): A language primarily for artificial intelligence research, introducing concepts like
recursion and symbolic computation.
ALGOL (1960s): Influential in the development of subsequent languages, ALGOL introduced
structured programming, which emphasized the use of loops, conditionals, and blocks of code.

1.4.4.3 The Advent of Structured Programming


C (1972): Developed at Bell Labs, C became one of the most widely used programming languages due
to its efficiency and portability. It introduced structured programming, which improved code readability
and maintenance.
Pascal (1970): Designed for teaching programming, Pascal emphasized structured programming and
data structuring.

1.4.4.4 Object-Oriented Programming (OOP)


Smalltalk (1972): One of the first object-oriented programming languages, Smalltalk introduced
concepts like objects, classes, and inheritance.
C++ (1983): An extension of C that added object-oriented features, C++ became popular for system
and application development.
Java (1995): Developed by Sun Microsystems, Java emphasized portability (write once, run anywhere)
and became widely used in web development and enterprise applications.

1.4.4.5 Modern and Scripting Languages


Python (1991): Known for its simplicity and readability, Python became popular for scripting,
automation, data analysis, and web development.
JavaScript (1995): Initially developed for client-side web development, JavaScript has evolved into a
versatile language used in full-stack development with frameworks like Node.js.
Ruby (1995): Emphasizing simplicity and productivity, Ruby became popular with the Ruby on Rails
web development framework.
1.4. PROGRAM DEVELOPMENT LIFE CYCLE (PDLC) 15

1.4.4.6 Contemporary Languages


Go (2007): Go is a statically typed, compiled high-level programming language designed at Google
by Robert Griesemer, Rob Pike, and Ken Thompson.
1
Swift (2014): Developed by Apple, Swift is designed for iOS and macOS development, emphasizing

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.

1.4.5 Evolution of Compilers


1.4.5.1 Early Compilers
FORTRAN Compiler (1957): One of the first high-level language compilers, the FORTRAN compiler
was a significant milestone, translating human-readable code into machine code. 2.2 Optimization and
Efficiency
Optimization Techniques (1960s-1970s): As computing resources were scarce, compilers began
to incorporate optimization techniques to generate more efficient machine code. This included loop
optimization, dead code elimination, and register allocation.

1.4.5.2 Intermediate Representations


Intermediate Code (1970s-1980s): Compilers began using intermediate representations of code,
which allowed for more sophisticated optimization techniques and easier portability across different
machine architectures.

1.4.5.3 Just-In-Time Compilation


Java Just-In-Time (JIT) Compiler (1990s): Java popularized the concept of Just-In-Time (JIT)
compilation, where bytecode is compiled into native machine code at runtime, combining the benefits of
interpreted and compiled languages.

1.4.5.4 Modern Compiler Developments


LLVM (2003): The LLVM project introduced a modular and reusable compiler infrastructure, which
has been widely adopted in modern programming languages like Swift and Rust.
Parallel and Distributed Compilation (2000s-Present): With the rise of multi-core processors
and distributed systems, modern compilers have evolved to support parallel and distributed compilation,
improving build times and performance.

1.4.6 Evolution of Interpreters


1.4.6.1 Early Interpreters
BASIC (1960s): One of the earliest and most popular interpreted languages, BASIC (Beginner’s All-
purpose Symbolic Instruction Code) was designed for ease of use and became widely used in educational
settings.
16 1.5. CROSS COMPILING

1.4.6.2 Scripting Languages


1 Shell Scripts (1970s): Unix shell interpreters allowed users to write scripts to automate tasks, making
interpreters an essential tool for system administration.
Perl (1987): Perl became popular for text processing and web development, with its interpreter
PGDCA103: PROGRAMMING WITH PYTHON

allowing for rapid script execution.

1.4.6.3 Bytecode Interpreters


Java Virtual Machine (JVM) (1995): The JVM interprets Java bytecode, allowing Java programs
to run on any platform with a compatible JVM. This concept of platform independence made Java a
revolutionary language.
Python Interpreter: Python’s interpreter executes Python code line by line, making it easy to test and
debug code interactively.

1.4.6.4 Just-In-Time (JIT) Interpreters


Dynamic Languages (2000s-Present): Languages like JavaScript and Python have evolved to use JIT
compilation techniques in their interpreters, combining the speed of compiled code with the flexibility of
interpreted code.

1.4.6.5 Modern Interpreter Trends


WebAssembly (2017): WebAssembly introduced a new kind of interpreter that allows code written in
multiple languages to run on the web at near-native speed, changing the landscape of web development.
Interpreters in Embedded Systems: Interpreters are increasingly used in embedded systems and IoT
devices, where flexibility and ease of deployment are critical.
The evolution of programming languages, compilers, and interpreters is a continuous process driven
by the need for more efficient, reliable, and easy-to-use tools. As technology advances, these tools will
continue to evolve, shaping the future of software development.

Sec 1.5 Cross Compiling

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.

1.5.1 Key Concepts of Cross-Compiling


1. Host System: The machine on which the compilation is performed. This is where the cross-compiler
runs.

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.

1.5.2 Why Cross-Compiling is Necessary


• Resource Constraints: Some target systems, such as embedded devices, have limited processing
power, memory, or storage, making it impractical to compile code directly on the device.

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

1.5.3 Examples of Cross-Compiling


• Embedded Systems: Developers often cross-compile code on a desktop or server for deployment on
microcontrollers, routers, or IoT devices running on different architectures like ARM or MIPS.

• Mobile Applications: When developing mobile applications, cross-compilation allows developers to


compile code on a desktop for Android (ARM) or iOS devices.

• Operating Systems: Building operating systems, like Linux distributions, often involves cross-
compiling to create binaries for various target architectures (e.g., ARM, x86, PowerPC).

1.5.4 Challenges of Cross-Compiling


• Dependency Management: Ensuring that all dependencies (libraries, header files, etc.) are available
and compatible with the target system can be complex.

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

1.5.5 Toolchains for Cross-Compiling


• GCC (GNU Compiler Collection): GCC supports cross-compiling for a wide range of architectures.
Developers can build or download cross-compiling toolchains for specific target platforms.

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

Cross-compiling is an essential technique in modern software development, particularly for embedded


PGDCA103: PROGRAMMING WITH PYTHON

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.

Sec 1.6 Concept of TDD

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.

1.6.1 Advantages of TDD


• Improved Code Quality: TDD leads to cleaner, more maintainable code since tests guide the design
and structure of the code.
• Early Bug Detection: By writing tests first, bugs are caught early in the development process,
reducing the cost and effort of fixing them later.
1.6. CONCEPT OF TDD 19

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

1.6.2 Challenges of TDD


• Learning Curve: TDD requires a shift in mindset and can be challenging for developers who are
used to writing code first and testing later.

• 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

Sec 2.1 Python Distributions

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.

3. ActivePython Description: A commercially supported distribution, optimized for enterprise environ-


ments. Features: Includes ActiveState’s package manager (PPM), precompiled binaries, commercial
support. Installation: Download from activestate.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.1.1 Features of Python


1. Easy to Learn and Use: Simple syntax resembling English, readability, and ease of writing.

2. Interpreted Language: No need to compile code before execution, which simplifies the development
process.

3. Dynamically Typed: No need to declare variable types explicitly.

4. Extensive Libraries: Large standard library and numerous third-party packages.

5. Portability: Runs on various platforms without modification (Windows, MacOS, Linux).

6. Object-Oriented: Supports classes and objects.

2.1.2 History and Versions


• Created by: Guido van Rossum, first released in 1991.

• 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

2.1.3 Applications of Python


1. Web Development: Frameworks like Django, Flask. 2
2. Data Science and Machine Learning: Libraries like NumPy, Pandas, Scikit-learn, TensorFlow.

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.1.4 Working in Console and Python Shell


1. Python Console: Interactive mode in terminal/command prompt where you can execute Python
commands directly.
2. Python Shell: Interactive development environment, such as IDLE, Jupyter Notebook, or other
REPL (Read-Eval-Print Loop) environments.

Sec 2.2 Basic Syntax

1. Variables: No need to declare types; assigned dynamically.


1 x = 5
2 y = "Hello"
3
4

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

3. Numbers and Strings


1
2 num = 10 # Integer
3 pi = 3.14 # Float
4 name = "John" # String
5
6
7
24 2.2. BASIC SYNTAX

4. Booleans
2 1
2
is_active = True
is_closed = False
3
PGDCA103: PROGRAMMING WITH PYTHON

5. Operators

(a) Arithmetic Operators: +, -, *, /, //, %, **


(b) Comparison Operators: ==, !=, >, <, >=, <=
(c) Logical Operators: and, or, not
(d) Assignment Operators: =, +=, -=, *=, /=
(e) Bitwise Operators: &, |, ^, ~, «, »

6. Converting Data Types


int(), float(), str(), bool()
1 x = "123"
2 y = int(x) # Converts string to integer
3
4
Sec 2.3 References

1. Introduction to Computing and Problem-Solving Using Python, E. Balaguruswamy

2. Learning To Program With Python Richard L Halterman

3. Martin C. Brown, Python: The Complete Reference.

4. https://onlinecourses.nptel.ac.in/noc23_cs20/preview
IHRD H ANDBOOKS

A Handbook series for IHRD PGDCA.

IHRD

You might also like