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

Python 1

The document provides a comprehensive introduction to Python and SageMath, covering fundamental concepts such as data types, variables, operators, and programming exercises. It includes sections on different modes of using Python, operator precedence, and practical examples. Additionally, it features questions and exercises to reinforce learning and understanding of the material.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views162 pages

Python 1

The document provides a comprehensive introduction to Python and SageMath, covering fundamental concepts such as data types, variables, operators, and programming exercises. It includes sections on different modes of using Python, operator precedence, and practical examples. Additionally, it features questions and exercises to reinforce learning and understanding of the material.
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

FUNDAMENTALS OF PYTHON

AND SAGEMATH

Dr Gopakumar B
Government Victoria College
Palakkad
Table of Contents

1 Getting started with Python .................................... 3


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Two Modes of Using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Interactive Mode (Interpreter Mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Script Mode (Program Mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.3 Key Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 Rules for naming Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.4 Dynamic Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.5 Multiple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.6 Worked Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.2 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.4 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.1 Worked Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6.1 Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6.2 Intermediate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.1 Solution 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.2 Solution 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.3 Solution 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.4 Solution 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.5 Solution 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.8 Conceptual Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.10 Multiple Choice Questions (MCQs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.11 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.12 Python Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.12.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.12.2 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.12.3 Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.12.4 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.12.5 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.12.6 Worked Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.13 Python Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.13.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.13.2 Characteristics of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.13.3 Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.13.4 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.13.5 Modifying Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.13.6 Nested Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.13.7 Mutable and Immutable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.14 Differences Between Strings and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.15 Input from the Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.15.1 The input() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.15.2 Type Conversion of Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.15.3 Using eval() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.15.4 Reading Multiple Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.15.5 Worked Example: Area of a Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.15.6 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.15.8 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.15.9 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.15.10 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.15.11 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.16 Python Syntax: Colon and Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.16.1 Use of Colon (:) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.16.2 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.16.3 Importance of Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.16.4 Indentation Error Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.16.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

II
1.17 Controlling the Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.17.1 Types of Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.17.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.17.3 Conditional Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.17.4 Uses of controll statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.18 Iteration: for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.18.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.18.2 Using range() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.18.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.18.4 Iteration over Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.18.5 Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.18.6 Advanced Examples: Nested Loops and Patterns . . . . . . . . . . . . . . . . . . . . . . . 25
1.19 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.20 Conditional Execution: if, elif and else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.20.1 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.20.2 The if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.20.3 The if-elif-else Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.20.4 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.20.5 Nested Use with Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.21 Loop Control Statements: break and continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.21.1 The break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.21.2 The continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.21.3 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.21.4 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.21.5 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.21.6 Identify Error or Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.21.7 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.22 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.22.2 Definition and Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.22.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.22.4 Advantages of a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.22.5 Scope of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.22.6 Optional and Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.22.7 Note: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.22.8 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.22.9 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.22.10 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.22.11 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.22.12 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

III
1.23 Python Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.23.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.23.3 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.23.4 Different Ways to Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.23.5 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.23.6 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.24 File Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.2 Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.3 Reading from a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.4 Writing to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.5 Appending to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.6 Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.24.7 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.25 Exercises: File Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.3 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.4 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.25.6 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.25.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.26 Formatted Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.26.1 General Rules of Formatted Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.26.2 Using Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.26.3 Formatting Floating Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.26.4 Using format() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.26.5 Alignment and Width . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.26.6 Common Errors and Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.27 Exercises: Formatted Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.27.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.27.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.27.3 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.27.4 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.27.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.27.6 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.27.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

IV
1.28 Matrices in Pure Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.28.2 Representation of Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.28.3 Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.28.4 Matrix Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.28.5 Scalar Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
1.28.6 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
1.28.7 Transpose of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
1.28.8 Determinant of a Matrix (2x2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.28.9 Inverse of a Matrix (2x2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.28.10 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.29 Exercises: Matrices in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.29.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.29.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.29.3 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.29.4 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.29.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.29.6 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.29.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.30 NumPy Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.30.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.30.2 Importing NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.30.3 Creating Arrays from Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.30.4 Slicing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
1.30.5 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1.31 Exercises: NumPy Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1.31.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1.31.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
1.31.3 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
1.31.4 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
1.31.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
1.31.6 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.31.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.32 Vectorizing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.32.2 Need for Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.32.3 Example without Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
1.32.4 Example with Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
1.32.5 Vectorizing User-defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
1.32.6 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
1.32.7 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
V
1.33 Exercises: Vectorizing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.3 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.4 Higher Order Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.33.6 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

2 Data visualization .......................................................... 67


2.1 The Matplotlib Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.1.1 Importing Required Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.1.2 Plotting Interfaces in Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.1.3 Basic 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
2.1.4 Polar Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
2.1.5 Multiple plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
2.2 Exercises: Matplotlib Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.2.1 Very Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.2.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.2.3 Programming Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.2.4 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
2.2.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
2.2.6 Higher Order Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.3 Plotting mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.3.1 Generating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.4 Plotting Error Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.4.1 Error Bar Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.4.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
2.5 Simple 2D Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.5.1 Using the animation Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.5.2 Example: Animated Sine Wave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.5.3 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.6 Famous Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
2.6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
2.6.2 Astroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
2.6.3 Ellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
2.6.4 Spirals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.6.5 Spirograph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.6.6 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
2.7 2D plot using colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
2.7.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

VI
2.8 Exercises: Plotting Mathematical Functions and Visualization . . . . . . . . . . . 84
2.8.1 Very Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.8.2 Short Answer Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.8.3 Programming Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.8.4 MCQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.8.5 Error Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2.8.6 Higher Order Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
2.9 3D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
2.9.1 Importing 3D Toolkit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
2.9.2 meshgrid() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
2.9.3 Computing Z Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
2.9.4 Creating 3D Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
2.9.5 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
2.9.6 Important Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
2.9.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

3 Symbolic Computation, SymPy ........................... 91


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.1.1 SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.1.2 Features of SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.1.3 Symbolic vs Numerical Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.1.4 Typical Workflow in SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.1.5 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.2 The SymPy Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.2.1 Importing SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.2.2 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.2.3 Advantages of SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.2.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3 Formatting the Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3.1 Default Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.4 Simplification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.4.1 Basic Simplification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.4.2 Expand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.4.3 Factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.4.4 Collect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.4.5 Importance of Simplification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.5 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.5.1 Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.5.2 Higher Order Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5.3 Partial Derivatives (Multiple Variables) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

VII
3.5.4 Higher Order Partial Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5.5 General Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.5.6 Using Derivative Object and doit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.5.7 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.5.8 Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.5.9 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.6 Excercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.6.1 Very Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.6.2 Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.6.3 Long Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.6.4 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

4 Introduction to Pandas ............................................ 101


4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
4.2 Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
4.2.1 Creating a Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
4.2.2 Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
4.2.3 Series from Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
4.2.4 Operations on Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4.2.5 .dropna() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4.2.6 Name Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
4.2.7 Properties of a Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
4.2.8 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
4.3 DataFrame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
4.3.1 DataFrame from a Numpy array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
4.3.2 DataFrame from a Dictionary of Pandas Series . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.3.3 DataFrame from a Dictionary of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.3.4 Saving DataFrames to CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
4.3.5 Reading DataFrames from CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
4.3.6 Index and Column Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
4.3.7 Column Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
4.3.8 Indexing and Slicing Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
4.3.9 Adding a Row . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.4 Concatenating DataFrames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
4.4.1 Arithmetic of DataFrames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
4.4.2 Excercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

5 Welcome to Sage! ........................................................ 123


5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.2 Basic Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
VIII
5.3 Simple Interest Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.4 Exponents in Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.5 Important Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.5.1 No Commas in Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.5.2 Explicit Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.5.3 Matching Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.6 Grouping Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.7 Editing Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.8 Common Mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.9 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.10 Using Sage with Common Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.10.1 Built-in Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.10.2 Square Roots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.10.3 N() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.10.4 Numerical Approximation using N() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.10.5 Higher Order Roots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.10.6 Special Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.10.7 Tab Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.10.8 Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.10.9 Exponentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.10.10 Logarithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
5.10.11 Square Roots (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
5.10.12 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.10.13 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.11 Using Sage for Trigonometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.11.1 Basic Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.11.2 Working in Radians . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.11.3 Decimal Approximations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
5.11.4 Undefined Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
5.11.5 Reciprocal Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
5.11.6 Inverse Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
5.11.7 Alternative Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
5.11.8 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.12 Matrices and Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.12.1 Row Reduces Echelon Form of a Matrix (RREF) . . . . . . . . . . . . . . . . . . . . . 132
5.13 Using Sage to Manipulate Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
5.14 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
5.14.1 Short Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
5.14.2 Long Answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
5.14.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

IX
5.15 Plotting Graphs in SageMath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.15.2 Basic Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.15.3 Basic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.15.4 Plotting Multiple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15.5 Controlling the Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15.6 Common Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15.7 Plot Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15.8 Implicit Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
5.16 Differentiation in SageMath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.16.2 Basic Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.16.3 Basic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.16.4 Higher Order Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.16.5 Derivatives of Standard Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.16.6 Product Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.7 Quotient Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.8 Chain Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.9 Evaluating Derivatives at a Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.10 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.11 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.16.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
5.17 Antiderivatives (Indefinite Integrals) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.17.1 Basic Syntax in SageMath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.17.2 Basic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.17.3 Standard Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.17.4 Constant of Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.17.5 Linearity of Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.17.6 Substitution (Basic Idea) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.17.7 Verification of Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
5.18 Riemann Sums and Definite Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.2 Partition of an Interval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.3 Riemann Sum (General Form) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.4 Definite Integral as a Limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.5 SageMath Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.18.6 Interpretation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

X
5.19 Riemann Sum Using Left Endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.1 Left Endpoint Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.2 Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.3 SageMath Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.4 Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.5 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.6 Table Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.7 Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.19.8 Comparison with Exact Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

XI
MODULE I
CHAPTER 1
Getting started with Python

1.1 Introduction
Python is a high-level, interpreted programming language widely used due to its sim-
plicity and readability. This module introduces:

⋄ Modes of using Python


⋄ Variables and data types
⋄ Operators and precedence

1.2 Two Modes of Using Python


Python programs can be executed in two different modes: Interactive Mode and
Script Mode.

1.2.1 Interactive Mode (Interpreter Mode)


Definition: Interactive mode is a way of executing Python statements one at a time,
where each statement is executed immediately after it is entered.
Example:
>>> x = 10
>>> y = 5
>>> x + y
15

Features:

⋄ Immediate execution of commands


⋄ No need to save code in a file
⋄ Useful for testing and learning

Limitation:

⋄ Not suitable for large programs


Chapter 1. Getting started with
Python 1.3. Variables and Data Types

1.2.2 Script Mode (Program Mode)


Definition: Script mode is a way of executing Python programs by writing a sequence
of statements in a file (called a script) with extension .py, and then executing the
entire file.
Example:
# file : example . py
x = 10
y = 5
print (" Sum =" , x + y )

Execution:
python example . py

Features:

⋄ Entire program executes at once


⋄ Code is stored permanently
⋄ Suitable for large and complex programs
⋄ Easier debugging and maintenance

Note: A Python file executed in script mode is called a Python script.

1.2.3 Key Differences

Feature Interactive Mode Script Mode


Execution Line-by-line Whole program
Storage Not saved Saved as file
Use Testing Development
Error Handling Immediate After execution

1.3 Variables and Data Types


1.3.1 Variables
A variable stores data.
x = 100
name = " Alice "

1.3.2 Rules for naming Variables


A variable name

⋄ Must start with letter or underscore


⋄ Cannot use keywords
⋄ is Case-sensitive

4 Government Victoria College


Chapter 1. Getting started with
1.3. Variables and Data Types Python

1.3.3 Data Types


Definition: A data type specifies the kind of value a variable can hold and determines
the set of operations that can be performed on that value.
In Python, every value belongs to a specific data type, and the type is determined
automatically at runtime. This is known as dynamic typing.
Example:
x = 10 # integer
y = 3.14 # float
name = " Ram " # string
flag = True # boolean

Explanation:

⋄ The variable x stores an integer value.


⋄ The variable y stores a decimal (floating-point) value.
⋄ The variable name stores text (a string).
⋄ The variable flag stores a logical value (boolean).

Importance of Data Types


⋄ They determine how data is stored in memory.
⋄ They define the operations allowed on the data.
⋄ They help avoid errors during program execution.

[Link] Basic Data Types in Python


1. Integer (int) Represents whole numbers (positive, negative, or zero).
a = 25
b = -10

2. Float (float) Represents real numbers with decimal points.


x = 3.75
y = -0.001

3. String (str) Represents a sequence of characters enclosed in quotes.


s1 = " Hello "
s2 = ’ Python ’

4. Boolean (bool) Represents logical values: True or False.


flag1 = True
flag2 = False

[Link] Type Identification


The built-in function type() is used to identify the data type of a variable.

Government Victoria College 5


Chapter 1. Getting started with
Python 1.4. Operators

print ( type (10) ) # < class ’int ’ >


print ( type (3.14) ) # < class ’ float ’ >
print ( type (" Hi ") ) # < class ’str ’ >

[Link] Type Conversion


Python allows conversion between data types.
int (3.9) # 3
float (5) # 5.0
str (100) # "100"

Note: During conversion, some information may be lost (e.g., converting float to
int removes the decimal part).

1.3.4 Dynamic Typing

x = 10
x = " Python "

Explanation: Type changes automatically.

1.3.5 Multiple Assignment


More than one variables can be assigned values in a single statement.
a, b, c = 1, 2, 3

1.3.6 Worked Examples


Example 1
x = 5
y = 2.5
print ( x + y )

Output: 7.5
Example 2
x = "5"
y = "3"
print ( x + y )

Output: 53

1.4 Operators
1.4.1 Arithmetic Operators

6 Government Victoria College


Chapter 1. Getting started with
1.5. Operator Precedence Python

Operator Meaning Example


+ Addition 2+3=5
- Subtraction 5-2=3
* Multiplication 3*4=12
/ Division 5/2=2.5
// Floor Division 5//2=2
% Modulus 5%2=1
** Power 2**3=8

1.4.2 Relational Operators

Operator Meaning
== Equal
!= Not equal
> Greater
< Less
>= Greater or equal
<= Less or equal

1.4.3 Logical Operators

Operator Meaning
and Logical AND
or Logical OR
not Logical NOT

1.4.4 Assignment Operators

x = 5
x += 3
x *= 2

1.5 Operator Precedence


(1) ()
(2) **
(3) *, /, //, %
(4) +, -
(5) Relational
(6) Logical

Government Victoria College 7


Chapter 1. Getting started with
Python 1.6. Programming Exercises

1.5.1 Worked Examples


Example 1
2 + 3 * 4

Answer: 14
Example 2
(2 + 3) * 4

Answer: 20
Example 3
5 + 2 * 3 ** 2

Solution:
32 = 9, 2 × 9 = 18, 5 + 18 = 23

1.6 Programming Exercises


1.6.1 Basic
Write a program to

(1) Add two numbers


(2) Find square of a number
(3) Convert temperature from Celsius to Fahrenheit

1.6.2 Intermediate
Write a program to

(1) Find remainder when one number is divided by another


(2) Check whether a number is greater than 10

1.7 Solutions
1.7.1 Solution 1

a = 10
b = 20
print ( a + b )

1.7.2 Solution 2

n = 5
print ( n * n )

8 Government Victoria College


Chapter 1. Getting started with
1.8. Conceptual Questions Python

1.7.3 Solution 3

c = 30
f = (9/5) * c + 32
print ( f )

1.7.4 Solution 4

print (10 % 3)

1.7.5 Solution 5

x = 15
print ( x > 10)

1.8 Conceptual Questions


(1) Difference between interactive and script mode
(2) What is dynamic typing?
(3) Explain operator precedence
(4) Difference between / and //

1.9 Summary
⋄ Python supports two execution modes
⋄ Variables are dynamically typed
⋄ Multiple data types exist
⋄ Operators perform computations
⋄ Precedence controls evaluation

1.10 Multiple Choice Questions (MCQs)


Choose the correct answer
(1) Which mode executes Python code line by line?

(a) Script mode (c) Compile mode


(b) Interactive mode (d) Debug mode

(2) Which of the following is not a valid data type in Python?

Government Victoria College 9


Chapter 1. Getting started with 1.10. Multiple Choice Questions
Python (MCQs)

(a) int (c) real


(b) float (d) str

(3) What is the output of 5 // 2?

(a) 2.5 (c) 3


(b) 2 (d) Error

(4) Which operator is used for exponentiation?

(a) ^ (c) //
(b) ** (d) %

(5) What is the type of "123"?

(a) int (c) str


(b) float (d) bool

(6) Which function is used to check data type?

(a) check() (c) type()


(b) typeof() (d) datatype()

(7) What is the output of 2 + 3 * 4?

(a) 20 (c) 24
(b) 14 (d) 10

(8) Which operator gives remainder?

(a) / (c) %
(b) // (d) **

(9) Python variables are:

(a) Statically typed (c) Constant


(b) Dynamically typed (d) None

(10) What is the output of True and False?

(a) True (c) Error


(b) False (d) None

Answers

10 Government Victoria College


Chapter 1. Getting started with
1.11. Short Answer Questions Python

(1) (b) (3) (b) (5) (c) (7) (b) (9) (b)
(2) (c) (4) (b) (6) (c) (8) (c) (10) (b)

1.11 Short Answer Questions


(1) What is Python? Why is it popular?
(2) What are the two modes of using Python?
(3) What is the difference between interactive and script mode?
(4) What is a variable?
(5) Explain dynamic typing with an example.
(6) List basic data types in Python.
(7) What is type conversion?
(8) What is the difference between int and float?
(9) Explain arithmetic operators with examples.
(10) What is the difference between / and //?
(11) What is operator precedence?
(12) Why are parentheses used in expressions?
(13) What are logical operators?
(14) What is the use of the type() function?
(15) Can a variable change its type in Python? Explain.
(16) What is multiple assignment?
(17) What happens when we add two strings?
(18) What is the modulus operator?
(19) What is the result of 3**2?
(20) What are relational operators?

1.12 Python Strings


1.12.1 Definition
A string is a sequence of characters enclosed in quotes.
s = " Python "

1.12.2 Characteristics
⋄ Strings are immutable
⋄ Indexed starting from 0
⋄ Support slicing

Government Victoria College 11


Chapter 1. Getting started with
Python 1.12. Python Strings

1.12.3 Indexing and Slicing


Strings support element access operations, whereby individual characters can be ex-
tracted using indexing, and substrings can be obtained using slicing. Example:
s = " Python "
print ( s [0]) # First character
print ( s [3]) # Fourth character

Output:
P
h

Explanation:

⋄ s[0] gives the first character.


⋄ s[3] gives the character at index 3.

Negative indexing allows accessing elements of a string starting from the end. The last
character of the string has index -1, the second last has index -2, and so on.
Explanation: While positive indexing starts from the beginning (left to right),
negative indexing starts from the end (right to left), which is useful when the length
of the string is not known.
Example:
s = " Python "
print ( s [ -1]) # Last character
print ( s [ -2]) # Second last character
print ( s [ -6]) # First character

Output:
n
o
P

Illustration:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Important Notes:

⋄ Negative indexing is useful for accessing elements from the end.


⋄ -1 always refers to the last element.
⋄ Helps avoid calculating string length.

String slicing is the process of extracting a portion (substring) of a string using a


specified range of indices.
Syntax:

12 Government Victoria College


Chapter 1. Getting started with
1.12. Python Strings Python

string [ start : end : step ]

Explanation:

⋄ start: Index where slicing begins (inclusive)


⋄ end: Index where slicing ends (exclusive)
⋄ step: Interval between characters (optional)

Example 1: Basic Slicing


s = " Python "
print ( s [0:3])

Output:
Pyt

Example 2: Omitting Start or End


print ( s [:4]) # from beginning
print ( s [2:]) # till end

Output:
Pyth
thon

Example 3: Using Step


print ( s [0:6:2])

Output:
Pto

Example 4: Negative Slicing


print ( s [ -4: -1])

Output:
tho

Example 5: Reversing a String


print ( s [:: -1])

Output:
nohtyP

Important Notes:

⋄ The end index is excluded


⋄ Default step is 1
⋄ Negative step reverses direction
⋄ Slicing does not modify the original string

Government Victoria College 13


Chapter 1. Getting started with
Python 1.12. Python Strings

1.12.4 String Operations


Definition: String Addition
Concatenation is the process of combining two or more strings into a single string.
In Python, this is done using the + operator.
When the + operator is applied to strings, it joins them end-to-end without adding
any extra space between them unless explicitly specified.
Example:
a = " Hello "
b = " World "
print ( a + b ) # HelloWorld

[Link] Repetition: Multiplication with a string


Repetition is the process of repeating a string multiple times to form a new string. In
Python, this is achieved using the * operator.
When a string is multiplied by an integer, the string is repeated that many times.
The integer specifies how many copies of the string are concatenated together.
Example:
s = " Hi "
print ( s * 3)

Output:
HiHiHi

Note:

⋄ The repetition operator works only when one operand is a string and the other
is an integer.
⋄ If the integer is 0, the result is an empty string.

Additional Example:
print (" A " * 5)
print (" Hello " * 2)

Output:
AAAAA
Hello Hello

1.12.5 String Functions

len (" Python ")


" abc ". upper ()
" ABC ". lower ()

14 Government Victoria College


Chapter 1. Getting started with
1.13. Python Lists Python

1.12.6 Worked Examples


Example 1
s = " Hello "
print ( s [:: -1])

Output: olleH

1.13 Python Lists


1.13.1 Definition
A list is a collection of elements enclosed in square brackets [ ], where elements are
separated by commas. The individual elements can be of any type, even another list.
L = [1 , 2 , 3 , 4]

Explanation:

⋄ Lists can store multiple values in a single variable.


⋄ Elements in a list can be of different data types.

L = [1 , " Python " , 3.5 , True ]

1.13.2 Characteristics of Lists


⋄ Lists are ordered
⋄ Lists are mutable (can be modified)
⋄ Allow duplicate elements
⋄ Support indexing and slicing

1.13.3 Accessing Elements


[Link] Indexing

L = [10 , 20 , 30 , 40]
print ( L [0])
print ( L [ -1])
print ( L [ -2])

Output:
10
40
30

Government Victoria College 15


Chapter 1. Getting started with
Python 1.13. Python Lists

[Link] Slicing
Python supports slicing of lists in the same way as strings, since both are sequence
data types.
print ( L [1:3])

Output:
[20 , 30]

1.13.4 List Operations


List addition and multiplication in Python are similar to those of strings, as both
support concatenation and repetition operations.

[Link] Concatenation

A = [1 , 2]
B = [3 , 4]
print ( A + B )

Output:
[1 , 2 , 3 , 4]

[Link] Repetition

print ([1 , 2] * 3)

Output:
[1 , 2 , 1 , 2 , 1 , 2]

1.13.5 Modifying Lists

L = [10 , 20 , 30]
L [1] = 99
print ( L )

Output:
[10 , 99 , 30]

1.13.6 Nested Lists


Definition: A nested list is a list that contains one or more lists as its elements.
Example:
L = [[1 , 2] , [3 , 4] , [5 , 6]]

16 Government Victoria College


Chapter 1. Getting started with
1.13. Python Lists Python

Accessing Elements: Elements of a nested list can be accessed using multiple


indices.
print ( L [0]) # First sublist
print ( L [0][1]) # Element inside first sublist

Output:
[1 , 2]
2

Explanation:

⋄ L[0] gives the first inner list


⋄ L[0][1] gives the second element of the first inner list

Use: Nested lists are useful for representing matrices, tables, and multi-dimensional
data.

1.13.7 Mutable and Immutable Types


Definition:

⋄ Mutable types are data types whose values can be changed after creation.
⋄ Immutable types are data types whose values cannot be changed once they
are created.

[Link] Mutable Types


Explanation: In mutable objects, we can modify elements without changing the
identity of the object.
Example:
L = [1 , 2 , 3]
L [0] = 10
print ( L )

Output:
[10 , 2 , 3]

Common Mutable Types:

⋄ list
⋄ dictionary
⋄ set

[Link] Immutable Types


Explanation: In immutable objects, the value cannot be modified after creation. Any
operation creates a new object.
Example:

Government Victoria College 17


Chapter 1. Getting started with 1.14. Differences Between Strings and
Python Lists

s = " Python "


# s [0] = ’J ’ # Error

Explanation: Strings do not allow modification of individual characters.


Common Immutable Types:

⋄ int
⋄ float
⋄ string
⋄ tuple

[Link] Comparison
Feature Mutable Immutable
Modification Allowed Not allowed
Memory Same object modified New object created
Examples list, set int, string
Important Note: Understanding mutability is important when working with
functions and data structures, as it affects how data is stored and modified.

1.14 Differences Between Strings and Lists


Feature String List
Mutability Immutable Mutable
Enclosed between Quotes Square brackets
Example "abc" [1,2,3]

1.15 Input from the Keyboard


Most programs require input from the user during execution. In Python, this is
achieved using the input() function.

1.15.1 The input() Function


Definition: The input() function reads data entered by the user from the keyboard
and returns it as a string.
Syntax:
input (" message ")

Example:
name = input (" Enter your name : ")
print (" Hello " , name )

Note: The argument of input() is optional and is used as a prompt message.

18 Government Victoria College


Chapter 1. Getting started with
1.15. Input from the Keyboard Python

1.15.2 Type Conversion of Input


Since input() returns a string, it must be converted to other data types if required.
x = int ( input (" Enter an integer : ") )
y = float ( input (" Enter a number : ") )

1.15.3 Using eval() Function


Explanation: The eval() function evaluates the input string as a Python expression
and returns the corresponding value.
Example:
x = eval ( input (" Enter an integer : ") )
y = complex ( input (" Enter a complex number : ") )
print (" The sum is " , x + y )

Note:

⋄ eval() can convert input into different data types automatically.


⋄ It should be used carefully, as it may execute unintended expressions.

1.15.4 Reading Multiple Inputs


It is possible to read multiple values in a single statement.
x , y = eval ( input (" Enter x and y separated by comma : ") )
print (" The sum is " , x + y )

1.15.5 Worked Example: Area of a Circle

pi = 3.1416
r = float ( input (" Enter radius : ") )
area = pi * r ** 2
print (" Area =" , area )

Explanation:

⋄ r ** 2 computes the square of the radius


⋄ ** has higher precedence than *
⋄ Formula used: A = πr2

1.15.6 Important Notes


⋄ input() always returns a string
⋄ Use int(), float() for safe conversion
⋄ eval() is powerful but should be used with caution
⋄ Invalid input to eval() may cause errors

Government Victoria College 19


Chapter 1. Getting started with
Python 1.15. Input from the Keyboard

1.15.7 Exercises
(1) Read two numbers and print their sum
(2) Input a number and print its square
(3) Input radius and compute area of circle
(4) Read two numbers using a single input statement

1.15.8 Short Answer Questions


(1) What is the index of the last element of a list?
(2) What does s[::-1] do?
(3) Is a string mutable? Justify.
(4) What is the difference between + and * for lists?
(5) What does L[-2] represent?
(6) What does input() return?
(7) Why is type conversion required?
(8) What is eval()?
(9) Difference between input() and eval(input())
(10) What happens when a string is multiplied by 2?
(11) Explain indexing and slicing with examples.
(12) What is negative indexing? Illustrate with a string.
(13) Distinguish between mutable and immutable data types.
(14) Explain list concatenation and repetition with examples.
(15) What is a nested list? How are elements accessed?

1.15.9 MCQs
(a) input() returns

(a) int (b) float (c) str (d) bool

(b) Which function evaluates expression?

(a) input() (b) eval() (c) type() (d) print()

(c) "5" * 2 gives

(a) 10 (b) 25 (c) 55 (d) Error

(d) Which of the following is mutable?

(a) string (b) tuple (c) list (d) int

(e) Output of [1,2]*2 is

20 Government Victoria College


Chapter 1. Getting started with
1.15. Input from the Keyboard Python

1,2,1,2 2,4 (a) Error (b) None

(f) Which of the following supports slicing?

(a) string (b) list (c) both (d) none

Answers: (c), (b), (c), (c), (a), (c)

1.15.10 Programming Exercises


(1) Write a program to print the first and last character of a string.
(2) Write a program to count the number of characters in a string.
(3) Input a string and print it in reverse order.
(4) Create a list of numbers and print the sum of all elements.
(5) Write a program to find the largest element in a list.
(6) Input a list and print only the even numbers.
(7) Write a program to swap the first and last elements of a list.
(8) Create a nested list and print all elements row-wise.
(9) Input a string and count the number of vowels.
(10) Write a program to check whether a string is a palindrome.
(11) Write a program to remove duplicate elements from a list.
(12) Write a program to find the frequency of each character in a string.
(13) Given a list, create another list containing squares of each element.
(14) Given a nested list, find the sum of all elements.
(15) Write a program to input a string and print alternate characters.
(16) Create a list of 10 numbers and print them in reverse order.
(17) Write a program to input a list and find the minimum and maximum elements.
(18) Write a program to generate a multiplication table using lists.
(19) Create a 2D list (matrix) and print its elements.

1.15.11 Error Identification


(1) Identify the error:
s = " Python "
s [0] = ’J ’

(2) What is the output?


L = [1 ,2 ,3]
print ( L *2)

(3) What is the output?


s = " Hi "
print ( s + 5)

Government Victoria College 21


Chapter 1. Getting started with 1.16. Python Syntax: Colon and
Python Indentation

(4) Identify the error:


L = [1 ,2 ,3]
print ( L [3])

1.16 Python Syntax: Colon and Indentation


Python uses a simple and readable syntax. Unlike many other programming languages,
Python does not use braces { } to define blocks of code. Instead, it uses a combination
of the colon (:) and indentation.

1.16.1 Use of Colon (:)


Definition: A colon (:) is used at the end of statements that introduce a block of
code.
Examples:
if x > 0:
print (" Positive ")

for i in range (5) :


print ( i )

def add (a , b ) :
return a + b

Explanation:

⋄ The colon indicates the beginning of a block.


⋄ It is used in statements like if, for, while, and def.

1.16.2 Indentation
Definition: Indentation refers to the spaces at the beginning of a line of code. It is
used to define the structure and grouping of statements into blocks.
Example:
if x > 0:
print (" Positive ")
print (" Valid number ")

Explanation:

⋄ All statements with the same indentation belong to the same block.
⋄ Typically, 4 spaces are used for indentation.

1.16.3 Importance of Indentation


⋄ Indentation replaces braces used in other languages.

22 Government Victoria College


Chapter 1. Getting started with
1.17. Controlling the Program Flow Python

⋄ It improves readability of code.


⋄ Incorrect indentation leads to errors.

1.16.4 Indentation Error Example

if x > 0:
print (" Positive ") # Error

Explanation: This will produce an IndentationError because the statement


inside the block is not properly indented.

1.16.5 Summary
⋄ Colon (:) is used to start a block of code.
⋄ Indentation defines the structure of the program.
⋄ Proper indentation is mandatory in Python.

1.17 Controlling the Program Flow


In a program, statements are normally executed sequentially from top to bottom.
However, to solve practical problems, it is necessary to control the order of execution.
This is achieved using control flow statements.

1.17.1 Types of Control Flow


Python provides two main types of control flow mechanisms:

⋄ Iteration (Loops): Used to repeat a set of statements multiple times.


⋄ Conditional Execution: Used to execute statements based on certain condi-
tions.

1.17.2 Iteration
Iteration allows a block of code to be executed repeatedly. Python provides two looping
constructs:

⋄ while loop
⋄ for loop

1.17.3 Conditional Execution


Conditional execution allows different actions based on conditions. It is implemented
using:

⋄ if
⋄ elif

Government Victoria College 23


Chapter 1. Getting started with
Python 1.18. Iteration: for Loops

⋄ else

These statements evaluate logical conditions and execute the corresponding block
of code.

1.17.4 Uses of controll statements


Control flow statements change the normal sequential execution of a program by in-
troducing loops and conditions. They are essential for writing meaningful and efficient
programs. They

⋄ enable decision-making in programs


⋄ allow repetition of tasks
⋄ make programs more flexible and powerful

1.18 Iteration: for Loops


The for loop in Python is used for iterating over a sequence such as a list, string, or
a range of numbers. It provides a convenient way to repeat a block of code for each
element in the sequence.

1.18.1 Syntax

for variable in sequence :


statements

1.18.2 Using range() Function


The range() function is commonly used with for loops to generate a sequence of
integer values.

⋄ range(n) generates numbers from 0 to n-1


⋄ range(a, b) generates numbers from a to b-1
⋄ range(a, b, step) generates numbers with a specified step

1.18.3 Examples
Example 1:
for i in range (5) :
print ( i )

Output:
0
1
2

24 Government Victoria College


Chapter 1. Getting started with
1.18. Iteration: for Loops Python

3
4

Example 2:
for i in range (1 , 6) :
print ( i * 2)

1.18.4 Iteration over Strings

for ch in " Python ":


print ( ch )

1.18.5 Uses
The for loop is a powerful and simple construct for iteration in Python. It is especially
useful when the number of iterations is known in advance or when traversing elements
of a sequence. It reduces chances of infinite loops It is

⋄ used to iterate over sequences.


⋄ automatically handles loop control.

1.18.6 Advanced Examples: Nested Loops and Patterns


[Link] Nested Loops
Definition: A loop inside another loop is called a nested loop. The inner loop
executes completely for each iteration of the outer loop.
Example: Multiplication Table
for i in range (1 , 4) :
for j in range (1 , 4) :
print ( i *j , end =" ") # prints in the same line
print () # Goes to a new line

Output:
1 2 3
2 4 6
3 6 9

Explanation:

⋄ Outer loop controls rows


⋄ Inner loop controls columns

[Link] Pattern Printing


Example 1: Right Triangle Pattern

Government Victoria College 25


Chapter 1. Getting started with
Python 1.18. Iteration: for Loops

for i in range (1 , 6) :
print ("*" * i )

Output:
*
**
***
****
*****

Example 2: Inverted Triangle


for i in range (5 , 0 , -1) :
print ("*" * i )

Output:
*****
****
***
**
*

Example 3: Pyramid Pattern


n = 5
for i in range (1 , n +1) :
print (" "*( n - i ) + "*"*(2* i -1) )

Output:
*
***
*****
*******
*********

Example 4: Number Pattern


for i in range (1 , 6) :
for j in range (1 , i +1) :
print (j , end =" ")
print ()

Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

26 Government Victoria College


Chapter 1. Getting started with
1.19. The while Loop Python

[Link] Important Notes


⋄ Nested loops are useful for working with matrices and patterns
⋄ The total number of iterations increases with nesting
⋄ Proper indentation is essential

1.19 The while Loop


Definition: The while loop is used to repeatedly execute a block of statements as
long as a given condition remains true.

Syntax

while condition :
statements

Explanation:

⋄ The condition is evaluated before each iteration.


⋄ If the condition is true, the block of statements is executed.
⋄ The loop continues until the condition becomes false.

Example

i = 1
while i <= 5:
print ( i )
i = i + 1

Output:
1
2
3
4
5

Important Points
⋄ The while loop is an entry-controlled loop.
⋄ The loop may not execute even once if the condition is false initially.
⋄ It is also called a condition-controlled loop.

Infinite Loop
If the condition never becomes false, the loop runs indefinitely.

Government Victoria College 27


Chapter 1. Getting started with 1.20. Conditional Execution: if, elif
Python and else

while True :
print (" Hello ")

Note: Care must be taken to update the condition inside the loop to avoid infinite
loops. The while loop is used when the number of iterations is not known in advance
and depends on a condition.

1.20 Conditional Execution: if, elif and else


In many situations, a program needs to execute certain statements only when a given
condition is satisfied. This is called conditional execution. Python provides this
feature using the keywords if, elif, and else.

1.20.1 The if Statement


Syntax:
if condition :
statements

Explanation:

⋄ The condition is evaluated.


⋄ If it is true, the corresponding block is executed.
⋄ If false, the block is skipped.

Example:
x = input (" Enter a string ")
if x == " hello ":
print (" You typed " , x )

1.20.2 The if-else Statement


Syntax:
if condition :
statements1
else :
statements2

Explanation:

⋄ If the condition is true, statements1 are executed.


⋄ Otherwise, statements2 are executed.

Example:

28 Government Victoria College


1.20. Conditional Execution: if, elif Chapter 1. Getting started with
and else Python

x = int ( input (" Enter a number ") )


if x % 2 == 0:
print (" Even ")
else :
print (" Odd ")

1.20.3 The if-elif-else Structure


Syntax:
if condition 1:
statements
elif condition 2:
statements
elif condition 3:
statements
.
.
.
elif condition n :
statements
else :
statements

Explanation:

⋄ The conditions are evaluated from top to bottom.


⋄ If the first condition is true, the corresponding block is executed and the remain-
ing conditions are skipped.
⋄ If the first condition is false, the next elif condition is checked.
⋄ This process continues until a true condition is found.
⋄ If none of the conditions are true, the else block is executed.

Example:
x = eval ( input (" Enter a number ") )
if x > 10:
print (" Bigger Number ")
elif x < 10:
print (" Smaller Number ")
else :
print (" Same Number ")

1.20.4 Important Points


⋄ Only one block among if, elif, and else is executed.
⋄ All these statements must have the same indentation level.
⋄ Conditions can be written in compact form, e.g., 10 < x < 15.

Government Victoria College 29


Chapter 1. Getting started with 1.21. Loop Control Statements: break
Python and continue

1.20.5 Nested Use with Loops


Conditional statements can be used inside loops.
x = 1
while x < 11:
if x < 5:
print (" Small " , x )
else :
print (" Big " , x )
x = x + 1

1.21 Loop Control Statements: break and continue


In addition to loops, Python provides special statements to control the execution of
loops. Loop control statements provide additional control over loop execution. These
are called loop control statements. The most commonly used ones are break and
continue. The break statement terminates the loop, while the continue statement
skips the current iteration and continues with the next.

1.21.1 The break Statement


Definition: The break statement is used to terminate a loop immediately, even if the
loop condition is still true.
Example:
for i in range (5) :
if i == 3:
break
print ( i )

Output:
0
1
2

Explanation:

⋄ When i becomes 3, the loop stops.


⋄ Remaining iterations are not executed.

1.21.2 The continue Statement


Definition: The continue statement skips the remaining part of the current iteration
and proceeds to the next iteration.
Example:
for i in range (5) :
if i == 2:

30 Government Victoria College


1.21. Loop Control Statements: break Chapter 1. Getting started with
and continue Python

continue
print ( i )

Output:
0
1
3
4

Explanation:

⋄ When i is 2, that iteration is skipped.


⋄ The loop continues with the next value.

1.21.3 Important Points


⋄ break exits the loop completely.
⋄ continue skips only the current iteration.
⋄ Both can be used in for and while loops.

1.21.4 Very Short Answer


(1) What is the use of the break statement?
(2) What does the continue statement do?
(3) Can break be used in a while loop?
(4) What happens when continue is executed?
(5) Which statement terminates the loop completely?
(6) Explain the break statement with an example.
(7) Explain the continue statement with an example.
(8) Distinguish between break and continue.
(9) What is the effect of using break inside a loop?
(10) How does continue affect loop execution?

1.21.5 Programming Exercises


(1) Write a program to print numbers from 1 to 10, but stop when the number is 6.
(2) Write a program to print numbers from 1 to 10, skipping multiples of 3.
(3) Write a program to search for a number in a list and stop when it is found.
(4) Write a program to print only odd numbers from 1 to 20 using continue.
(5) Write a program that repeatedly asks for input and stops when the user enters
0.
(6) Write a program to find the first number divisible by both 3 and 5 in a given
range.
(7) Given a list, print elements until a negative number is encountered.

Government Victoria College 31


Chapter 1. Getting started with 1.21. Loop Control Statements: break
Python and continue

(8) Write a program to count how many numbers were skipped using continue.
(9) Write a program to simulate a password check that stops after correct input.
(10) Write a program to print numbers from 1 to 50, skipping numbers divisible by 5.
(11) Write a program to keep accepting input until the user enters "exit".
(12) Write a program to find the first prime number in a given range.
(13) Write a program to simulate a menu-driven system using a loop and break.

1.21.6 Identify Error or Output


(1) Identify the error:
for i in range (5) :
if i == 3:
continue
print ( i )
break

(2) What is the output?


for i in range (5) :
if i == 2:
break
print ( i )

(3) What is the output?


for i in range (5) :
if i % 2 == 0:
continue
print ( i )

(4) Identify the error:


if i == 2:
break

1.21.7 MCQs
(1) Which statement terminates the loop?

(a) continue (b) break (c) pass (d) exit

(2) Which statement skips the current iteration?

(a) break (b) continue (c) skip (d) next

(3) Output of:


for i in range (5) :
if i == 3:

32 Government Victoria College


Chapter 1. Getting started with
1.22. Functions Python

break
print ( i )

(a) 0 1 2 (b) 0 1 2 3 (c) 1 2 3 (d) 0 1

(4) Output of:


for i in range (5) :
if i == 2:
continue
print ( i )

(a) 0 1 2 3 4 (b) 0 1 3 4 (c) 1 2 3 (d) Error

Answers: (b), (b), (a), (b)

1.22 Functions
1.22.1 Introduction
A function is a reusable block of code that performs a specific task. It helps in orga-
nizing programs into smaller and manageable parts.

1.22.2 Definition and Syntax


Functions in Python are defined using the def keyword.
def function_name ( parameters ) :
statements
return value

Explanation:

⋄ def is used to define a function


⋄ Parameters are optional inputs to the function
⋄ The function body is indented
⋄ return sends the result back

1.22.3 Example

def add (a , b ) :
return a + b

print ( add (2 , 3) )

Government Victoria College 33


Chapter 1. Getting started with
Python 1.22. Functions

1.22.4 Advantages of a function


⋄ Functions improve code reuse
⋄ They make programs modular

1.22.5 Scope of Variables


The scope of a variable refers to the region of a program where the variable can be
accessed.

[Link] Local Variables


A variable defined inside a function is called a local variable. It is accessible only
within that function.
def test () :
x = 10 # local variable
print ( x )

test ()

Explanation:

⋄ The variable x is created inside the function.


⋄ It cannot be accessed outside the function.

[Link] Global Variables


A variable defined outside all functions is called a global variable. It can be accessed
throughout the program.
x = 20 # global variable

def show () :
print ( x )

show ()

Explanation:

⋄ The variable x is defined outside the function.


⋄ It is accessible inside the function.

[Link] Local vs Global


⋄ A local variable exists only within the function.
⋄ A global variable exists throughout the program.
⋄ If a variable with the same name is defined inside a function, it hides the global
variable.

34 Government Victoria College


Chapter 1. Getting started with
1.22. Functions Python

x = 5

def f () :
x = 10
print ( x )

f ()
print ( x )

Output:
10
5

Explanation:

⋄ The local variable x = 10 is used inside the function.


⋄ The global variable x = 5 remains unchanged.

[Link] Modifying Global Variables


To modify a global variable inside a function, the global keyword is used.
x = 5

def f () :
global x
x = 10

f ()
print ( x )

Output:
10

[Link] Key Points


⋄ Local variables are defined inside functions.
⋄ Global variables are defined outside functions.
⋄ Local variables have limited scope.
⋄ Global variables can be accessed everywhere.
⋄ The global keyword allows modification of global variables inside functions.

1.22.6 Optional and Named Arguments


Functions can have default values for parameters.
def greet ( name =" User ") :
print (" Hello " , name )

Government Victoria College 35


Chapter 1. Getting started with
Python 1.22. Functions

Named arguments allow calling functions with parameter names.


greet ( name =" Ajith ")

1.22.7 Note:
Functions are used to divide programs into smaller units, making them easier to un-
derstand and reuse. A function may or may not return a value

1.22.8 Short Answer Questions


(1) What is a function?
(2) Which keyword is used to define a function?
(3) What is the use of return?
(4) What are parameters?
(5) What is a local variable?
(6) Explain functions with an example.
(7) What is the difference between parameters and arguments?
(8) Explain scope of variables.
(9) What are default arguments?
(10) What are named arguments?

1.22.9 Programming Exercises


(1) Write a function to find the sum of two numbers.
(2) Write a function to check whether a number is even or odd.
(3) Write a function to find factorial of a number.
(4) Write a function with default argument to print a greeting.
(5) Write a function to find the maximum of three numbers.

1.22.10 Higher Order Problems


(1) Write a function to compute the sum of elements of a list.
(2) Write a function to check whether a string is a palindrome.
(3) Write a function to count vowels in a string.
(4) Write a function that returns both sum and product of two numbers.
(5) Write a program to calculate area of a circle using a function.
(6) Write a function to reverse a string.
(7) Write a function to check prime numbers.

1.22.11 Error Identification


(1) Identify the error:
def add (a , b )
return a + b

36 Government Victoria College


Chapter 1. Getting started with
1.23. Python Modules and Packages Python

(2) Identify the error:


def f () :
print (" Hello ")

(3) What is the output?


def f () :
return 5

print ( f () )

(4) What is the error?


def f (a , b ) :
print ( a + b )

f (2)

1.22.12 MCQs
(a) Which keyword is used to define a function?

(a) func (b) def (c) function (d) define

(b) What does a function return if no return statement is given?

(a) 0 (b) None (c) Error (d) Empty

(c) Which of the following is a valid function call?

(a) f[ ] (b) f( ) (c) call f (d) func f

(d) Variables inside a function are:

(a) global (b) local (c) static (d) external

Answers: (b), (b), (b), (b)

1.23 Python Modules and Packages


1.23.1 Introduction
A module is a file containing Python definitions and statements. Modules help in
organizing programs and reusing code.
A package is a collection of related modules arranged in directories.
Modules and packages help in structuring programs and reusing code efficiently.

Government Victoria College 37


Chapter 1. Getting started with
Python 1.23. Python Modules and Packages

1.23.2 Modules
Definition: A module is a Python file (with .py extension) that contains functions,
variables, or classes.
Example:
# file : mymodule . py
def add (a , b ) :
return a + b

1.23.3 Importing Modules


Modules can be used in another program using the import statement.
Example:
import mymodule
print ( mymodule . add (2 ,3) )

1.23.4 Different Ways to Import


⋄ import module
⋄ import module as alias
⋄ from module import name

Examples:
import math
print ( math . sqrt (16) )

import math as m
print ( m . sqrt (25) )

from math import sqrt


print ( sqrt (36) )

1.23.5 Packages
A package is a directory containing multiple modules.

1.23.6 Advantages
⋄ Code reusability
⋄ Better organization
⋄ Easier maintenance

38 Government Victoria College


Chapter 1. Getting started with
1.24. File Input/Output Python

1.24 File Input/Output


1.24.1 Introduction
File Input/Output (I/O) functions allow a program to read data from a file and write
data to a file, enabling permanent storage and retrieval of information.

1.24.2 Opening a File


A file is opened using the open() function.
f = open (" filename " , " mode ")

Modes:

⋄ "r" : Read mode


⋄ "w" : Write mode (creates or overwrites file)
⋄ "a" : Append mode

1.24.3 Reading from a File

f = open (" data . txt " , " r ")


data = f . read ()
print ( data )
f . close ()

1.24.4 Writing to a File

f = open (" data . txt " , " w ")


f . write (" Hello World ")
f . close ()

1.24.5 Appending to a File

f = open (" data . txt " , " a ")


f . write (" New Line ")
f . close ()

1.24.6 Closing a File


After completing operations, the file must be closed using close().
f . close ()

1.24.7 Important Points


⋄ Files must be opened before use
⋄ Always close the file after use

Government Victoria College 39


Chapter 1. Getting started with
Python 1.25. Exercises: File Input/Output

⋄ Write mode overwrites existing content


⋄ Append mode adds content at the end

1.25 Exercises: File Input/Output


1.25.1 Very Short Answer
(1) What are file I/O functions in Python?
(2) Which function is used to open a file?
(3) What is the use of close()?
(4) What does mode "w" do?
(5) What is append mode?

1.25.2 Short Answer Questions


(1) Explain file opening modes.
(2) How do you read data from a file?
(3) How do you write data to a file?
(4) Why is it necessary to close a file?
(5) Distinguish between write and append modes.

1.25.3 Programming Exercises


(1) Write a program to create a file and write some text into it.
(2) Write a program to read and display contents of a file.
(3) Write a program to append data to an existing file.
(4) Write a program to count number of characters in a file.
(5) Write a program to copy contents from one file to another.

1.25.4 Higher Order Problems


(1) Write a program to count number of lines in a file.
(2) Write a program to count words in a file.
(3) Write a program to search for a word in a file.
(4) Write a program to read a file and display only uppercase letters.

1.25.5 Error Identification


(1) Identify the error:
f = open (" data . txt " , " r ")
f . write (" Hello ")

(2) Identify the error:

40 Government Victoria College


Chapter 1. Getting started with
1.26. Formatted Printing Python

f = open (" data . txt " , " w ")


f . read ()

(3) What is the output?


f = open (" data . txt " , " w ")
f . write (" Hi ")
f . close ()
print (" Done ")

(4) Identify the error:


open (" data . txt " , " r ")
f . read ()

1.25.6 MCQs
(a) Which function is used to open a file?

(a) file() (b) open() (c) read() (d) write()

(b) Which mode is used to append data?

(a) r (b) w (c) a (d) x

(c) What does read() do?

(a) writes file (b) reads file (c) deletes file (d) opens file

(d) Which mode overwrites the file?

(a) r (b) a (c) w (d) x

Answers: (b), (c), (b), (c)

1.25.7 Exercises
(1) Write a program to maintain student records using files.
(2) Write a program to read a file and display line by line.
(3) Write a program to copy file contents.
(4) Write a program to count vowels in a file.

1.26 Formatted Printing


Formatted printing improves readability and presentation of output. It allows control
over number format, alignment, and spacing.

Government Victoria College 41


Chapter 1. Getting started with
Python 1.26. Formatted Printing

1.26.1 General Rules of Formatted Printing


⋄ Use print() to display output.
⋄ Format specifiers (like %d, %f) control how values are displayed.
⋄ The number of format specifiers must match the number of values.
⋄ Data types must match the specifier (e.g., integer with %d).
⋄ Floating point numbers can be formatted using precision (e.g., %.2f).
⋄ The format() method provides a modern way to format output.
⋄ Alignment can be controlled using width and alignment symbols.

1.26.2 Using Format Specifiers


Example:
x = 10
y = 3.1416
print (" x = %d , y = % f " % (x , y ) )

Rule:

⋄ %d is used for integers


⋄ %f is used for floating point numbers

1.26.3 Formatting Floating Numbers


Example:
print ("%.2 f " % 3.1416)

Output:
3.14

Rule:

⋄ %.nf prints the number with n decimal places

1.26.4 Using format() Method


Example:
x = 10
y = 20
print (" x = {} , y = {}". format (x , y ) )

Rule:

⋄ Curly braces {} act as placeholders


⋄ Values are filled in order

42 Government Victoria College


Chapter 1. Getting started with
1.27. Exercises: Formatted Printing Python

1.26.5 Alignment and Width


Example:
print ("{:10}". format (" Hi ") )
print ("{: <10}". format (" Hi ") )
print ("{: >10}". format (" Hi ") )

Rule:

⋄ :10 → total width 10


⋄ :< → left alignment
⋄ :> → right alignment

1.26.6 Common Errors and Rules


⋄ Mismatch between format specifier and value causes error
⋄ Number of values must match placeholders
⋄ Wrong type (e.g., string with %d) gives error

1.27 Exercises: Formatted Printing


1.27.1 Very Short Answer
(1) What is formatted printing?
(2) Which function is used to print output?
(3) What does %d represent?
(4) What does %f represent?
(5) What is the use of format()?

1.27.2 Short Answer Questions


(1) Explain formatted printing with an example.
(2) What are format specifiers?
(3) How do you format floating point numbers?
(4) Explain alignment in formatted printing.
(5) Write a note on format() method.

1.27.3 Programming Exercises


(1) Write a program to print a number with two decimal places.
(2) Write a program to print a table of numbers using formatted output.
(3) Write a program to display aligned text.
(4) Write a program to print student details in formatted form.
(5) Write a program to format output using format() method.

Government Victoria College 43


Chapter 1. Getting started with
Python 1.27. Exercises: Formatted Printing

1.27.4 Higher Order Problems


(1) Write a program to display a formatted bill.
(2) Write a program to print a multiplication table using formatting.
(3) Write a program to display a report card with aligned columns.
(4) Write a program to format floating numbers in scientific notation.

1.27.5 Error Identification


(1) Identify the error:
print (" Value = % d " % "10")

(2) Identify the error:


print (" x = {} {}". format (10) )

(3) What is the output?


print ("%.1 f " % 2.567)

(4) Identify the error:


print ("{: d }". format (3.5) )

1.27.6 MCQs
(a) %d is used for:

(a) float (b) integer (c) string (d) boolean

(b) Output of:


print ("%.2 f " % 3.456)

(a) 3.45 (b) 3.46 (c) 3.4 (d) 3.456

(c) Which method is used for formatting?

(a) print() (b) input() (c) format() (d) read()

(d) %f is used for:

(a) integer (b) float (c) string (d) list

Answers: (b), (b), (c), (b)

44 Government Victoria College


Chapter 1. Getting started with
1.28. Matrices in Pure Python Python

1.27.7 Exercises
(1) Write a formatted student report.
(2) Print a formatted table of squares and cubes.
(3) Write a billing system using formatted output.
(4) Display aligned output using format().

1.28 Matrices in Pure Python


1.28.1 Introduction
A matrix is a two-dimensional arrangement of elements in rows and columns. In
Python, matrices can be represented using lists of lists.

1.28.2 Representation of Matrices


A matrix is represented as a list where each element is another list representing a row.
A = [[1 , 2 , 3] ,
[4 , 5 , 6] ,
[7 , 8 , 9]]

Rule:

⋄ Each inner list represents a row


⋄ Elements are accessed using row and column indices

1.28.3 Accessing Elements

print ( A [0][1]) # Output : 2

Rule:

⋄ First index → row


⋄ Second index → column

1.28.4 Matrix Addition


Example:
A = [[1 , 2] , [3 , 4]]

B = [[5 , 6] , [7 , 8]]

C = [[ A [ i ][ j ] + B [ i ][ j ] for j in range (2) ] for i in range (2) ]

print ( C )

Rule:

Government Victoria College 45


Chapter 1. Getting started with
Python 1.28. Matrices in Pure Python

⋄ Matrices must have the same dimensions


⋄ Add corresponding elements

1.28.5 Scalar Multiplication


Example:
A = [[1 , 2] ,
[3 , 4]]

k = 2

C = [[ k * A [ i ][ j ] for j in range (2) ] for i in range (2) ]


print ( C )

Rule:

⋄ Each element of the matrix is multiplied by the scalar value

1.28.6 Matrix Multiplication


Example:
A = [[1 , 2] , [3 , 4]]

B = [[5 , 6] , [7 , 8]]

C = [[0 , 0] , [0 , 0]]

for i in range (2) :


for j in range (2) :
for k in range (2) :
C [ i ][ j ] += A [ i ][ k ] * B [ k ][ j ]

print ( C )

Rule:

⋄ Number of columns of A = number of rows of B


⋄ Multiply row elements with column elements and sum

1.28.7 Transpose of a Matrix


Example:
A = [[1 , 2 , 3] , [4 , 5 , 6]]

T = [[ A [ j ][ i ] for j in range (2) ] for i in range (3) ]

print ( T )

Rule:

46 Government Victoria College


Chapter 1. Getting started with
1.29. Exercises: Matrices in Python Python

⋄ Rows become columns and columns become rows

1.28.8 Determinant of a Matrix (2x2)


Example:
A = [[ a , b ] , [c , d ]]
det = a * d - b * c
print ( det )

Rule:
" #
a b
⋄ Determinant of is ad − bc
c d

1.28.9 Inverse of a Matrix (2x2)


Example:
A = [[ a , b ] , [c , d ]]
det = a * d - b * c
inv = [[ d / det , -b / det ] , [ - c / det , a / det ]]
print ( inv )

Rule:

⋄ Inverse exists only if determinant ̸= 0


⋄ Formula:
1
" #
d −b
A −1
=
ad − bc −c a

1.28.10 Important Points


⋄ Matrices are implemented using nested lists
⋄ Indexing is used to access elements
⋄ Loops are used for matrix operations

1.29 Exercises: Matrices in Python


1.29.1 Very Short Answer
(1) What is a matrix?
(2) How is a matrix represented in Python?
(3) What is a nested list?
(4) How do you access matrix elements?
(5) What is transpose of a matrix?

Government Victoria College 47


Chapter 1. Getting started with
Python 1.29. Exercises: Matrices in Python

1.29.2 Short Answer Questions


(1) Explain matrix representation in Python.
(2) How do you access elements of a matrix?
(3) Explain matrix addition.
(4) Explain matrix multiplication.
(5) What is transpose of a matrix?

1.29.3 Programming Exercises


(1) Write a program to add two matrices.
(2) Write a program to multiply two matrices.
(3) Write a program to find transpose of a matrix.
(4) Write a program to display a matrix row-wise.
(5) Write a program to find sum of all elements in a matrix.
(6) Write a program to perform scalar multiplication of a matrix.
(7) Write a program to find determinant of a 2x2 matrix.
(8) Write a program to find inverse of a 2x2 matrix.
(9) Write a program to compute cross product of two vectors.

1.29.4 Higher Order Problems


(1) Write a program to check if a matrix is symmetric.
(2) Write a program to find diagonal elements of a matrix.
(3) Write a program to multiply a matrix by a scalar.
(4) Write a program to find row-wise and column-wise sums.

1.29.5 Error Identification


(1) Identify the error:
A = [[1 ,2] ,[3 ,4]]
print ( A [2][1])

(2) Identify the error:


A = [1 ,2 ,3]
print ( A [1][0])

(3) What is the output?


A = [[1 ,2] ,[3 ,4]]
print ( A [1][1])

(4) Identify the error:


A = [[1 ,2] ,[3 ,4]]
B = [[5 ,6]]
C = A + B

48 Government Victoria College


Chapter 1. Getting started with
1.30. NumPy Arrays Python

1.29.6 MCQs
(1) A matrix in Python is:

(a) a string (b) a list of lists (c) a tuple (d) a function

(2) Accessing element in row 1, column 2:

(a) A[1][2] (b) A[0][1] (c) A[2][1] (d) A[1][1]

(3) Matrix addition requires:

(a) same rows (b) same (c) same dimen- (d) same values
columns sions

(4) Transpose converts:

(a) rows to (b) columns to (c) both (d) none


columns rows

1 2
" #
(5) Determinant of is:
3 4
(a) -2 (b) 2 (c) 10 (d) -10

(6) Cross product is defined for:

(a) 2D vectors (b) 3D vectors (c) matrices (d) scalars

Answers: (b), (b), (c), (c),(a), (b)

1.29.7 Exercises
(1) Write a program for matrix addition using user input.
(2) Write a program for matrix multiplication.
(3) Write a program to find transpose.
(4) Write a program to check symmetric matrix.

1.30 NumPy Arrays


1.30.1 Introduction
NumPy is a Python library used for numerical computations. It provides support for
arrays of homogeneous data, which are more efficient than Python lists for mathemat-
ical operations.

Government Victoria College 49


Chapter 1. Getting started with
Python 1.30. NumPy Arrays

1.30.2 Importing NumPy


Before using NumPy functions, the NumPy module must be imported into the program
using the import statement.
import numpy as np

Rule:

⋄ The keyword import is used to include external modules.


⋄ NumPy is usually imported using the alias np

1.30.3 Creating Arrays from Lists


NumPy arrays can be created from Python lists using the [Link]() function.
Example:
import numpy as np
L = [1 , 2 , 3 , 4]
A = np . array ( L )
print ( A )

Rule:

⋄ A Python list can be converted into a NumPy array using [Link]().


⋄ The resulting array is homogeneous (all elements have the same data type).

[Link] Creating 2D Arrays from Nested Lists


A list of lists can be used to create a two-dimensional array.
Example:
L = [[1 , 2 , 3] , [4 , 5 , 6]]
A = np . array ( L )
print ( A )

Rule:

⋄ Each inner list represents a row of the array.


⋄ All inner lists must have the same length.
⋄ Elements are of same type (homogeneous)

[Link] Creating Arrays using arange() Function


The arange() function in NumPy is used to create an array with evenly spaced values
within a specified range.

[Link] Syntax

np . arange ( start , stop , step )

50 Government Victoria College


Chapter 1. Getting started with
1.30. NumPy Arrays Python

[Link] Examples
Example 1:
import numpy as np
a = np . arange (5)
print ( a )

Output:
[0 1 2 3 4]

Example 2:
a = np . arange (1 , 6)
print ( a )

Output:
[1 2 3 4 5]

Example 3:
a = np . arange (0 , 10 , 2)
print ( a )

Output:
[0 2 4 6 8]

[Link] Rules
⋄ Generates values from start to stop−1
⋄ Default value of start is 0
⋄ Default value of step is 1
⋄ The stop value is not included

[Link] Important Points


⋄ Similar to Python’s range() but returns a NumPy array
⋄ Can also work with floating point values

[Link] Creating Arrays using linspace() Function


NumPy arrays can be created using the linspace() function, which generates a spec-
ified number of evenly spaced values over a given interval.
Syntax:
np . linspace ( start , stop , num )

Examples:

Government Victoria College 51


Chapter 1. Getting started with
Python 1.30. NumPy Arrays

import numpy as np

a = np . linspace (0 , 1 , 5)
print ( a )

Output:
[0. 0.25 0.5 0.75 1. ]

a = np . linspace (1 , 5 , 4)
print ( a )

Output:
[1. 2.33333333 3.66666667 5. ]

Rules:

⋄ Generates num equally spaced values between start and stop


⋄ Both start and stop values are included
⋄ The spacing between values is calculated automatically

Note:

⋄ Unlike arange(), linspace() uses number of elements instead of step size


⋄ Commonly used when equal spacing is required

[Link] Creating Arrays using zeros() Function


NumPy arrays filled with zeros can be created using the zeros() function.
Syntax:
np . zeros ( shape )

Examples:
import numpy as np

a = np . zeros (5)
print ( a )

Output:
[0. 0. 0. 0. 0.]

b = np . zeros ((2 , 3) )
print ( b )

Output:
[[0. 0. 0.]
[0. 0. 0.]]

52 Government Victoria College


Chapter 1. Getting started with
1.30. NumPy Arrays Python

Rules:

⋄ The argument shape specifies the size of the array


⋄ A single value creates a 1D array
⋄ A tuple creates a multi-dimensional array
⋄ By default, elements are of float type

Note: zeros() is useful for initializing arrays

[Link] Creating Arrays using ones() Function


NumPy arrays filled with ones can be created using the ones() function.
Syntax:
np . ones ( shape )

Examples:
import numpy as np

a = np . ones (5)
print ( a )

Output:
[1. 1. 1. 1. 1.]

b = np . ones ((2 , 3) )
print ( b )

Output:
[[1. 1. 1.]
[1. 1. 1.]]

Rules:

⋄ The argument shape specifies the size of the array


⋄ A single value creates a 1D array
⋄ A tuple creates a multi-dimensional array
⋄ By default, elements are of float type

Note: ones() is useful for initializing arrays with ones

[Link] Creating Arrays using random() Function


NumPy provides functions in the random module to generate arrays with random
values.
Syntax:
np . random . random ( shape )

Government Victoria College 53


Chapter 1. Getting started with
Python 1.30. NumPy Arrays

Examples:
import numpy as np

a = np . random . random (5)


print ( a )

Output: (values will vary)


[0.23 0.75 0.11 0.89 0.45]

b = np . random . random ((2 , 3) )


print ( b )

Output: (values will vary)


[[0.12 0.56 0.78]
[0.34 0.91 0.67]]

Rules:

⋄ Generates random floating point numbers between 0 and 1


⋄ The argument shape specifies the size of the array
⋄ Output values change each time the program is executed

Note:

⋄ Part of NumPy’s random module


⋄ Useful for simulations and testing

[Link] reshape(array, newshape)


The reshape() function is used to change the shape of an array without changing its
data.
Syntax:
np . reshape ( array , newshape )

Examples:
import numpy as np

a = np . arange (6)
b = np . reshape (a , (2 , 3) )
print ( b )

Output:
[[0 1 2]
[3 4 5]]

c = np . reshape (a , (3 , 2) )
print ( c )

54 Government Victoria College


Chapter 1. Getting started with
1.30. NumPy Arrays Python

Output:
[[0 1]
[2 3]
[4 5]]

Rules:

⋄ The total number of elements must remain the same


⋄ New shape must be compatible with the original size
⋄ Reshaping does not change the data, only its arrangement

Note:

⋄ Can also be used as a method: [Link](newshape)


⋄ One dimension can be specified as -1, which is automatically calculated

Example with -1:


a = np . arange (6)
b = a . reshape (2 , -1)
print ( b )

Output:
[[0 1 2]
[3 4 5]]

[Link] Copying Arrays


Numpy arrays can be copied using the copy method. Using copy()
a = np . array ([1 , 2 , 3])
b = a . copy ()
c=a
c [0]=20
b [0] = 10
print ( a )
print ( b )

Output:
[20 2 3]
[10 2 3]

Explanation:

⋄ copy() creates a new independent array


⋄ Changes made to one array do not affect the other
⋄ Assignment creates a new reference to the same array (no new memory is allo-
cated)

Government Victoria College 55


Chapter 1. Getting started with
Python 1.30. NumPy Arrays

⋄ Changes made through one reference are reflected in the other

Rules:

⋄ Assignment creates a reference (no new memory)


⋄ copy() creates a new array (separate memory)
⋄ Use copy() when independent arrays are required

[Link] Saving and Restoring Arrays


NumPy provides functions to save arrays to files and load them back when required.
Arrays can be stored either in binary format or text format. This is useful for storing
data permanently.

Saving and Loading in Text Format


NumPy saves and loads data in text format using the savetxt() and loadtxt()
functions.

[Link] Syntax of savetxt() and loadtxt()


savetxt() Syntax:
np . savetxt ( filename , array , fmt , delimiter )

Explanation:

⋄ filename : Name of the file (e.g., "[Link]")


⋄ array : NumPy array to be saved
⋄ fmt : Format of elements (e.g., %d, %.2f)
⋄ delimiter : Separator between values (e.g., comma, space)

loadtxt() Syntax:
np . loadtxt ( filename , delimiter )

Explanation:

⋄ filename : Name of the file


⋄ delimiter : Separator used in the file

Example:
import numpy as np
a = np . array ([[2 ,3] , [4 ,5]])
print ( a )
np . savetxt ( ’ mydata . txt ’ , a , fmt = ’%2.3 f ’ , delimiter =
’ ’)
print ( ’ Data saved to text file ’)
b = np . loadtxt (" mydata . txt " , delimiter =" ")

56 Government Victoria College


Chapter 1. Getting started with
1.30. NumPy Arrays Python

print ( ’ Data loaded from text file ’)


print ( b )

Output

[[2 3]
[4 5]]
Data saved to text file
Data loaded from text file
[[ 2. 3.]
[ 4. 5.]]

Output File ([Link]):

2.000 3.000
4.000 5.000

Rules:

⋄ savetxt() saves array in text format


⋄ loadtxt() reads array from text file
⋄ Data is stored in human-readable form

1.30.4 Slicing Arrays


Slicing is used for extracting elements from an array. If a is a two dimensional Numpy
array,

⋄ a[i] extracts the entire row i. item a[:,j] extracts the entire column j.
⋄ a[i,j] extracts the element at (i+1)th row and (j+1)th column.
⋄ a[i,j:k] extracts the elements in the (i+1)th row from columns (j+1) to k.
⋄ a[i:k,j] extracts the elements in the (j+1)th column from rowss (i+1) to k.
⋄ a[:,:] extracts the entire array.

Example

x = np . reshape ( range (12) ,(4 ,3) )


print ( x [1])
print ( x [2 ,1])
print ( x [1:3 , 1])
print ( x [1 ,1:3])
print ( x [ : , 1])
print ( x [:2 ,:2])
print ( x [: , :])

Output

Government Victoria College 57


Chapter 1. Getting started with
Python 1.31. Exercises: NumPy Arrays

[3,4,5]

[4,7]

[4,5]

[ 1, 4, 7, 10]

[[0 1]
[3 4]]

[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]]
Rule:

⋄ Works similar to list slicing

1.30.5 Arithmetic Operations


NumPy arrays support various arithmetic operations.
If a and b are NumPy arrays and k is a scalar, then:

⋄ Element-wise addition: a + b
⋄ Element-wise subtraction: a - b
⋄ Scalar multiplication: a * k
⋄ Element-wise multiplication: a * b
⋄ Matrix multiplication: a @ b

To perform matrix multiplication, the NumPy function dot() or the array method
.dot() can also be used.
np . dot (a , b )
a . dot ( b )

Note: For matrix multiplication, the number of columns of the first array must be
equal to the number of rows of the second array.

1.31 Exercises: NumPy Arrays


1.31.1 Very Short Answer
(1) What is NumPy?

58 Government Victoria College


Chapter 1. Getting started with
1.31. Exercises: NumPy Arrays Python

(2) What is an array?


(3) How do you import NumPy?
(4) What does arange() do?
(5) What is reshape()?

1.31.2 Short Answer Questions


(1) Explain NumPy arrays.
(2) Differentiate between list and NumPy array.
(3) Explain linspace() function.
(4) What are zeros and ones arrays?
(5) Explain array slicing.

1.31.3 Programming Exercises


(1) Create a NumPy array of first 10 natural numbers.
(2) Create an array using linspace().
(3) Create a 3x3 zero matrix.
(4) Reshape a 1D array into 2D.
(5) Perform element-wise addition of two arrays.

1.31.4 Higher Order Problems


(1) Generate random arrays and compute their sum.
(2) Write a program to demonstrate array slicing.
(3) Compare performance of list vs NumPy array.
(4) Perform matrix operations using NumPy.
(5) Write a program to solve the system of equations using matrix inversion:

4x1 + 2x2 + x3 = 11
2x1 + 4x2 + 2x3 = 16
x1 + 2x2 + 4x3 = 17

1.31.5 Error Identification


(1) Identify the error:
import numpy
a = np . array ([1 ,2 ,3])

(2) Identify the error:


a = np . arange (5)
b = a . reshape ((2 ,3) )

(3) What is the output?

Government Victoria College 59


Chapter 1. Getting started with
Python 1.32. Vectorizing Functions

a = np . array ([1 ,2 ,3])


print ( a *2)

(4) Identify the error:


a = np . zeros (2 ,3)

1.31.6 MCQs
(a) NumPy arrays are:

(a) (b) (c) strings (d) functions


heterogeneous homogeneous

(b) arange(5) gives:

(a) 1–5 (b) 0–4 (c) 0–5 (d) error

(c) reshape() requires:

(a) same shape (b) same ele- (c) same size (d) same values
ments

(d) zeros((2,2)) creates:

(a) 1s (b) 0s (c) random (d) list

Answers: (b), (b), (c), (b)

1.31.7 Exercises
(1) Create and manipulate NumPy arrays.
(2) Perform arithmetic operations on arrays.
(3) Demonstrate reshape and slicing.
(4) Demonstrate save and load arrays.

1.32 Vectorizing Functions


1.32.1 Introduction
Vectorization is a technique used in NumPy to apply a function to all elements of an
array without using explicit loops.

1.32.2 Need for Vectorization


In Python, operations on lists often require loops, which are slower. NumPy allows
operations to be performed on entire arrays efficiently.

60 Government Victoria College


Chapter 1. Getting started with
1.32. Vectorizing Functions Python

1.32.3 Example without Vectorization

L = [1 , 2 , 3 , 4]
result = []
for x in L :
result . append ( x * 2)
print ( result )

1.32.4 Example with Vectorization

import numpy as np
a = np . array ([1 , 2 , 3 , 4])
print ( a * 2)

Output:
[2 4 6 8]

1.32.5 Vectorizing User-defined Functions


NumPy provides vectorize() to apply functions element-wise.
def square ( x ) :
return x * x

vfunc = np . vectorize ( square )


a = np . array ([1 , 2 , 3 , 4])
print ( vfunc ( a ) )

Output:
[1 4 9 16]

1.32.6 Rules
⋄ Vectorization avoids explicit loops
⋄ Operations are applied element-wise
⋄ Improves performance and readability

1.32.7 Advantages
⋄ Faster execution
⋄ Cleaner code
⋄ Efficient memory usage

Government Victoria College 61


Chapter 1. Getting started with
Python 1.33. Exercises: Vectorizing Functions

1.33 Exercises: Vectorizing Functions


1.33.1 Very Short Answer
(1) What is vectorization?
(2) Why is vectorization used?
(3) Which function is used to vectorize a function?
(4) Does vectorization require loops?
(5) What is the advantage of vectorization?

1.33.2 Short Answer Questions


(1) Explain vectorization with an example.
(2) Compare vectorized and non-vectorized code.
(3) What is [Link]()?
(4) What are advantages of vectorization?

1.33.3 Programming Exercises


(1) Write a program to multiply all elements of an array by 3 using vectorization.
(2) Write a vectorized function to compute square of numbers.
(3) Write a vectorized function to check even numbers.
(4) Write a program to apply a function to all elements of an array.

1.33.4 Higher Order Problems


(1) Write a vectorized function to compute factorial.
(2) Write a function and vectorize it for cube operation.
(3) Compare performance of loop vs vectorized approach.
(4) Apply vectorized function on 2D arrays.

1.33.5 Error Identification


(1) Identify the error:
a = np . array ([1 ,2 ,3])
print ( a * "2")

(2) Identify the error:


def f ( x ) :
return x * x
v = np . vectorize ( f )

(3) What is the output?


a = np . array ([1 ,2 ,3])
print ( a +2)

62 Government Victoria College


Chapter 1. Getting started with
1.33. Exercises: Vectorizing Functions Python

1.33.6 MCQs
(1) Vectorization means:

(a) loop execution (c) file operation


(b) element-wise operation (d) sorting

(2) [Link]() is used for:

(a) loops (c) file handling


(b) function application (d) plotting

(3) Output of:


a = np . array ([1 ,2])
print ( a *2)

(a) [2 4] (b) [1 2] (c) error (d) none

Answers: (b), (b), (a)

Government Victoria College 63


MODULE II
CHAPTER 2
Data visualization

Python provides libraries for graphical representation of data. One of the most com-
monly used libraries is matplotlib.

2.1 The Matplotlib Module


Matplotlib is a Python package used for creating high-quality graphical representations
of data. It can produce publication-quality figures in various formats such as PNG,
PDF, and SVG.
Using Matplotlib, one can generate different types of plots such as line graphs,
histograms, bar charts, scatter plots, power spectra, and error charts with only a
few lines of code. It also provides full control over line styles, fonts, axes, and other
graphical properties.
The data for plotting can be supplied as Python lists or NumPy arrays.
Matplotlib works using a hierarchical structure. It first creates a Figure object,
which represents the entire plotting area. Within the figure, one or more Axes objects
are created using the add_subplot() method. The actual plots are drawn inside the
Axes using functions such as plot().
Structure:
Figure → Axes → Plot

2.1.1 Importing Required Modules


Before creating plots, the required modules must be imported into the program.
import matplotlib . pyplot as plt

Explanation:

⋄ [Link] is the main module used for plotting


⋄ It is imported with the alias plt for convenience
⋄ All plotting functions such as plot(), show(), xlabel() are accessed using plt

2.1.2 Plotting Interfaces in Matplotlib


The sequence of creating a plot using the explicit approach is shown below:
import matplotlib . pyplot as plt
fig = plt . figure ()
Chapter 2. Data visualization 2.1. The Matplotlib Module

ax = fig . add_subplot ()
ax . plot ([1 ,2 ,3] , [10 ,12 ,15])
plt . show ()

However, for simple 2D plots, the plot() function can be used directly:
import matplotlib . pyplot as plt
plt . plot ([1 ,2 ,3] , [10 ,12 ,15])
plt . show ()

In this case, the Figure and Axes objects are automatically created and managed
by Matplotlib.

Explanation:

⋄ The first method is known as the explicit Axes interface, where Figure and
Axes objects are created manually.
⋄ The second method is called the implicit pyplot interface, where Matplotlib
handles object creation automatically.

Usage:

⋄ The implicit method is commonly used for simple 2D plots.


⋄ The explicit method is preferred when more control is required, such as:

– Creating multiple subplots


– Designing complex layouts
– Working with 3D plots or animations

2.1.3 Basic 2D Plotting


Matplotlib provides simple functions to create 2D plots. The most commonly used
function is plot().

[Link] Basic Line Plot

import matplotlib . pyplot as plt


x = [1 , 2 , 3 , 4]
y = [2 , 4 , 6 , 8]
plt . plot (x , y )
plt . show ()

Explanation:

⋄ x represents values on the x-axis


⋄ y represents values on the y-axis

68 Government Victoria College


2.1. The Matplotlib Module Chapter 2. Data visualization

⋄ plot() draws the graph


⋄ show() displays the graph

[Link] Adding Labels and Title

plt . xlabel (" X - axis ")


plt . ylabel (" Y - axis ")
plt . title (" Simple Line Graph ")

Rule:

⋄ Labels describe the axes


⋄ Title describes the graph

[Link] Changing Line Style

plt . plot (x , y , ’r - - ’)

Explanation:

⋄ r → red color
⋄ - - → dashed line

[Link] Plotting Multiple Lines

y2 = [1 , 3 , 5 , 7]
plt . plot (x , y )
plt . plot (x , y2 )
plt . show ()

Rule:

⋄ Multiple plot() calls draw multiple lines on the same graph

[Link] Important Points


⋄ Length of x and y must be equal
⋄ show() must be called to display the graph
⋄ Default plot is a line graph

[Link] Other Options of plot()


The plot() function provides several options to customize the appearance of a graph.
Line Color
plt . plot (x , y , color = ’ red ’)

Common colors: ’red’, ’blue’, ’green’, ’black’


Line Style

Government Victoria College 69


Chapter 2. Data visualization 2.1. The Matplotlib Module

plt . plot (x , y , linestyle = ’ - - ’)

Common styles:

⋄ ’-’ solid line


⋄ ’- -’ dashed line
⋄ ’:’ dotted line
⋄ ’-.’ dash-dot line

Marker Style
plt . plot (x , y , marker = ’o ’)

Common markers:

⋄ ’o’ circle
⋄ ’s’ square
⋄ ’^’ triangle
⋄ ’*’ star

Line Width
plt . plot (x , y , linewidth =2)

Combining Options
plt . plot (x , y , color = ’ blue ’ , linestyle = ’ - -’, marker = ’o
’)

Using Format String


plt . plot (x , y , ’ro - - ’)

Explanation:

⋄ r → red color
⋄ o → circle marker
⋄ - - → dashed line

Adding Grid
plt . grid ( True )

Legend
plt . plot (x , y , label =" Line 1")
plt . legend ()

70 Government Victoria College


2.1. The Matplotlib Module Chapter 2. Data visualization

2.1.4 Polar Plots


In polar plots, points are represented using polar coordinates (r, θ) instead of Cartesian
coordinates (x, y).

⋄ r represents the distance from the origin


⋄ θ represents the angle

Polar plots are useful for representing circular and periodic patterns.

[Link] Example: Polar Plot

import matplotlib . pyplot as plt


import numpy as np

theta = np . arange (0 , 2* np . pi , 0.1)


r = theta

plt . polar ( theta , r )


plt . show ()

Explanation:

⋄ theta contains angle values (in radians)


⋄ r contains corresponding radius values
⋄ polar() is used to draw polar plots

[Link] Example: Circle

theta = np . arange (0 , 2* np . pi , 0.1)


r = 2

plt . polar ( theta , [ r ]* len ( theta ) )


plt . show ()

Explanation:

⋄ Constant radius produces a circle

[Link] Important Points


⋄ Polar plots use (r, θ) instead of (x, y)
⋄ Angle must be in radians
⋄ polar() function is used instead of plot()

2.1.5 Multiple plots


Matplotlib allows us to display more than one graph in a single figure. This is done
using the subplot() function.

Government Victoria College 71


Chapter 2. Data visualization 2.1. The Matplotlib Module

[Link] Using subplot()


The syntax is:
plt . subplot ( nrows , ncols , index )

Explanation:

⋄ nrows → number of rows


⋄ ncols → number of columns
⋄ index → position of the current plot

[Link] Example: Two Plots

import matplotlib . pyplot as plt

x = [1 , 2 , 3 , 4]
y1 = [1 , 4 , 9 , 16]
y2 = [1 , 2 , 3 , 4]

plt . subplot (2 , 1 , 1)
plt . plot (x , y1 )

plt . subplot (2 , 1 , 2)
plt . plot (x , y2 )

plt . show ()

Explanation:

⋄ The figure is divided into 2 rows and 1 column


⋄ First plot is placed in position 1
⋄ Second plot is placed in position 2

[Link] Example: Side by Side Plots

plt . subplot (1 , 2 , 1)
plt . plot (x , y1 )

plt . subplot (1 , 2 , 2)
plt . plot (x , y2 )

plt . show ()

Explanation:

⋄ Two plots are placed in one row and two columns


⋄ They appear side by side

72 Government Victoria College


2.2. Exercises: Matplotlib Module Chapter 2. Data visualization

[Link] Important Points


⋄ subplot() divides the figure into a grid
⋄ Multiple graphs can be displayed in one window
⋄ Each subplot can have its own graph

2.2 Exercises: Matplotlib Module


2.2.1 Very Short Answer Questions
(1) What is Matplotlib?
(2) Which module is used for plotting in Python?
(3) What is the use of plot() function?
(4) What does show() do?
(5) What is a polar plot?
(6) What function is used for polar plots?
(7) What is a pie chart?
(8) What is the use of subplot()?
(9) What do you mean by multiple plots?
(10) What type of data is used in plotting functions?

2.2.2 Short Answer Questions


(1) Explain the Matplotlib module.
(2) What are the different types of plots supported by Matplotlib?
(3) Explain the structure of Matplotlib (Figure, Axes, Plot).
(4) Describe how to create a simple 2D plot.
(5) Explain polar plots with an example.
(6) What is a pie chart? Explain with example.
(7) Explain multiple plots using subplot().
(8) Differentiate between 2D plots and polar plots.

2.2.3 Programming Questions


(1) Write a program to plot a simple line graph.
(2) Plot the graph of y = x2 for x = 1 to 10.
(3) Write a program to draw a polar plot.
(4) Draw a circle using polar coordinates.
(5) Write a program to create a pie chart.
(6) Write a program to display two graphs using subplot().
(7) Plot two different functions on the same figure using multiple plots.

Government Victoria College 73


Chapter 2. Data visualization 2.2. Exercises: Matplotlib Module

2.2.4 MCQs
(a) Matplotlib is a:

(a) database (b) plotting li- (c) compiler (d) OS


brary

(b) Which function is used for line plots?

(a) draw() (b) plot() (c) show() (d) line()

(c) Which function displays the graph?

(a) display() (b) show() (c) plot() (d) print()

(d) Polar plots use:

(a) (x,y) (b) (r,θ) (c) (a,b) (d) (i,j)

(e) Which function is used for polar plots?

(a) plot() (b) polar() (c) pie() (d) bar()

(f) Which function is used to create multiple plots?

(a) multi() (b) subplot() (c) plot() (d) figure()

Answers: (b), (b), (b), (b), (b), (b)

2.2.5 Error Identification


(1) Identify the error:
import matplotlib
plt . plot ([1 ,2 ,3])

(2) Identify the error:


plt . plot ([1 ,2 ,3] ,[4 ,5])

(3) Identify the error:


plt . polar ([1 ,2 ,3])

(4) Identify the error:


plt . subplot (2 ,1 ,0)

74 Government Victoria College


2.3. Plotting mathematical functions Chapter 2. Data visualization

2.2.6 Higher Order Questions


(1) Compare different types of plots in Matplotlib.
(2) Explain how Matplotlib manages Figure and Axes.
(3) Write a program to display three different plots in one figure.
(4) Explain the importance of visualization in data analysis.

2.3 Plotting mathematical functions


One of the main objectives of plotting is to understand various mathematical functions
through graphical representation.
For this purpose, we use functions such as arange(), linspace() and logspace()
from the NumPy module to generate input data. These functions help in creating
sequences of values that are used for plotting. The mathematical functions are then
applied in their vectorized form on these data sets.

2.3.1 Generating Data


⋄ arange(start, stop, step) → generates values with given step size
⋄ linspace(start, stop, n) → generates n evenly spaced values
⋄ logspace(start, stop, n) → generates values on a logarithmic scale

[Link] Example Program-1


Plot the functions y = sin (x) and y1 = sin (x2 ) in the interval −π ≤ x ≤ π in the same
graph.
import numpy as np
import matplotlib . pyplot as plt

x = np . linspace ( - np . pi , np . pi , 200)

y = np . sin ( x )
y1 = np . sin ( x * x )

plt . plot (x , y )
plt . plot (x , y1 )

plt . show ()

[Link] Important Points


⋄ Input values range from −π to +π
⋄ linspace() is used to generate evenly spaced values
⋄ Vectorized functions like [Link]() operate on arrays

Government Victoria College 75


Chapter 2. Data visualization 2.3. Plotting mathematical functions

[Link] Example Program-2


Plot the unit circle x2 + y 2 = 1 using cartisian coordinates.
import numpy as np
import matplotlib . pyplot as plt

a = 1.0
x = np . linspace ( -a , a , 200)

yupper = np . sqrt ( a **2 - x **2)


ylower = - np . sqrt ( a **2 - x **2)

plt . plot (x , yupper )


plt . plot (x , ylower )

plt . show ()

Explanation:

⋄ x values range from −a to +a


⋄ yupper represents the upper half of the circle
⋄ ylower represents the lower half
⋄ Both curves are plotted to obtain the complete circle

[Link] Important Note


⋄ This method splits the circle into two parts
⋄ Such issues arise with multi-valued functions
⋄ Better approaches:
– Parametric equations
– Polar plots

[Link] Example Program-2


Plot the unit circle x2 + y 2 = 1 using parametric equation.
import numpy as np
import matplotlib . pyplot as plt

a = 1.0

th = np . linspace (0 , 2* np . pi , 200)

x = a * np . cos ( th )
y = a * np . sin ( th )

plt . plot (x , y )
plt . show ()

76 Government Victoria College


2.4. Plotting Error Bars Chapter 2. Data visualization

Explanation:

⋄ ’th’ represents the parameter θ


⋄ x and y are computed using cosine and sine functions
⋄ As θ varies from 0 to 2π, the full circle is traced

[Link] Advantages
⋄ Generates the complete circle in a single step
⋄ Avoids the problem of multi-valued functions
⋄ Produces a smooth and continuous curve

2.4 Plotting Error Bars


In many experiments, measured data contains some uncertainty or error. Error bars
are used in graphs to represent this uncertainty visually.
Error bars indicate the possible variation in the measured values and help in un-
derstanding the accuracy of data.

2.4.1 Error Bar Plot


Matplotlib provides the errorbar() function to plot data along with error values.
plt . errorbar (x , y , yerr = errors )

2.4.2 Example

import numpy as np
import matplotlib . pyplot as plt

x = np . array ([1 , 2 , 3 , 4 , 5])


y = np . array ([2 , 4 , 6 , 8 , 10])
err = np . array ([0.5 , 0.3 , 0.6 , 0.4 , 0.5])

plt . errorbar (x , y , yerr = err )

plt . show ()

Explanation:

⋄ x → independent variable
⋄ y → measured values
⋄ yerr → error in y-values
⋄ Error bars are drawn vertically

Government Victoria College 77


Chapter 2. Data visualization 2.5. Simple 2D Animation

Figure 2.1. Plot showing data points with vertical


error bars

2.5 Simple 2D Animation


Animation is the process of displaying a sequence of frames to create the illusion of
motion.
Matplotlib provides an animation module to create animations in a systematic
way.

2.5.1 Using the animation Module


To create animation, we use the FuncAnimation() function from the [Link]
module.

2.5.2 Example: Animated Sine Wave

import numpy as np
import matplotlib . pyplot as plt
from matplotlib . animation import FuncAnimation as fa
fig1 = plt . figure ()
ax = fig1 . add_subplot ()
x = np . linspace ( -2* np . pi , 2* np . pi , 100)
L , = ax . plot (x , np . sin ( x ) )
def update ( fnum ) :
L . set_data (x , np . sin ( x + 0.1 * fnum ) )
anim = fa ( fig1 , update , frames =100 , interval =50)
plt . show ()

2.5.3 Explanation
The given program demonstrates how to create a simple 2D animation using the
FuncAnimation() function from the Matplotlib animation module.

78 Government Victoria College


2.5. Simple 2D Animation Chapter 2. Data visualization

⋄ Importing Modules
import numpy as np
import matplotlib . pyplot as plt
from matplotlib . animation import
FuncAnimation as fa

NumPy is used for numerical data, Matplotlib for plotting, and FuncAnimation
is used to create animation.
⋄ Creating Figure and Axes
fig1 = plt . figure ()
ax = fig1 . add_subplot ()

A figure window is created and an axes object is added to it.


⋄ Generating Data
x = np . linspace ( -2* np . pi , 2* np . pi , 100)

Creates 100 evenly spaced values between −2π and 2π.


⋄ Initial Plot
L , = ax . plot (x , np . sin ( x ) )

Plots the initial sine wave. The comma is used to unpack the line object.
⋄ Update Function
def update ( fnum ) :
L . set_data (x , np . sin ( x + 0.1 * fnum ) )

This function updates the y-values of the plot.

– fnum represents the frame number


– The sine wave is shifted by changing the phase
– set_data() updates the graph without redrawing it completely

⋄ Creating Animation
anim = fa ( fig1 , update , frames =100 ,
interval =50)

– fig1 → figure object


– update → function called repeatedly

Government Victoria College 79


Chapter 2. Data visualization 2.6. Famous Curves

– frames=100 → number of frames


– interval=50 → delay between frames (in milliseconds)

⋄ Displaying the Animation


plt . show ()

Displays the animated plot.

2.6 Famous Curves


2.6.1 Introduction
Mathematical curves often exhibit interesting patterns and symmetries. Using Python
and Matplotlib, we can visualize such curves easily.
In this section, we explore some famous curves using parametric equations.

2.6.2 Astroid
The astroid is a special type of hypocycloid.
Parametric equations:
x = a cos3 t, y = a sin3 t

import numpy as np
import matplotlib . pyplot as plt

t = np . linspace (0 , 2* np . pi , 200)
a = 10

x = a * ( np . cos ( t ) ) **3
y = a * ( np . sin ( t ) ) **3

plt . plot (x , y )
plt . title (" Astroid ")
plt . show ()

2.6.3 Ellipse
Parametric equations:
x = a cos t, y = b sin t

import numpy as np
import matplotlib . pyplot as plt

t = np . linspace (0 , 2* np . pi , 200)

a = 10

80 Government Victoria College


2.6. Famous Curves Chapter 2. Data visualization

b = 5

x = a * np . cos ( t )
y = b * np . sin ( t )

plt . plot (x , y )
plt . title (" Ellipse ")
plt . show ()

2.6.4 Spirals
[Link] Archimedean Spiral
Polar equation:
r = aθ

import numpy as np
import matplotlib . pyplot as plt
a = 2
th = np . linspace (0 , 10 * np . pi ,200)
r = a * th
plt . polar ( th , r )
plt . axis ([0 , 2 * np . pi , 0 , 70])
plt . title (" Archimedean Spiral ")
plt . grid ( False )
plt . show ()

[Link] Fermat’s Spiral


Polar equation: √
r=a θ

import numpy as np
import matplotlib . pyplot as plt
a = 2
th = np . linspace (0 , 10 * np . pi ,200)
r = np . sqrt ( a **2 * th )
plt . polar ( th , r )
plt . grid ( False )
plt . show ()

2.6.5 Spirograph
Spirographs are generated by rolling one circle inside or outside another.
Parametric equations:

1−k
" !#
x (t) = R (1 − k) cos t + k cos t
k

Government Victoria College 81


Chapter 2. Data visualization 2.6. Famous Curves

1−k
" !#
y (t) = R (1 − k) sin t + k sin t
k

import numpy as np
import matplotlib . pyplot as plt
t = np . linspace (0 , 10 * np . pi , 500)
r = 3.
R = 10.0
k = r/R
l = 1.4
x = R *((1 - k ) * np . cos ( t ) + l * k * np . cos ((1 - k ) * t / k ) )
y = R *((1 - k ) * np . sin ( t ) - l * k * np . sin ((1 - k ) * t / k ) )
plt . plot (x , y )
plt . title (" Spirograph ")
plt . show ()

(a) Astroid (b) Ellipse

(c) Archimedean Spiral (d) Fermat’s Spiral (e) Spirograph

Figure 2.2. Examples of Famous Curves

2.6.6 Important Points


⋄ Parametric equations are useful for plotting complex curves
⋄ Many curves are generated using trigonometric functions
⋄ Visualization helps in understanding geometric properties

82 Government Victoria College


2.7. 2D plot using colors Chapter 2. Data visualization

2.7 2D plot using colors


Consider an m × n matrix A = [aij ]. Each element aij is assigned a colour based on
its value.
A rectangular grid with m rows and n columns is displayed on the screen. Each
cell (i, j) of the grid is coloured according to the value of aij .
Such a graphical representation of a matrix, where values are represented using
colours, is called a 2D colour plot.

[Link] Explanation
⋄ Each matrix element corresponds to one cell in the grid
⋄ Colours represent the magnitude of values
⋄ Different values produce different colours
⋄ The arrangement of colours reflects the structure of the matrix

[Link] Important Points


⋄ Used to visualize numerical data in matrix form
⋄ Helps in identifying patterns and variations
⋄ Commonly used in scientific and engineering applications

2.7.1 Example

import numpy as np
import matplotlib . pyplot as plt
m = np . random . random ([50 ,50])
plt . imshow ( m )
plt . show ()

Figure 2.3. 2D Color Plot

Government Victoria College 83


2.8. Exercises: Plotting Mathematical
Chapter 2. Data visualization Functions and Visualization

2.8 Exercises: Plotting Mathematical Functions and Vi-


sualization
2.8.1 Very Short Answer Questions
(1) What is linspace() used for?
(2) What is a vectorized function?
(3) Define even and odd functions.
(4) What is a parametric plot?
(5) What is a polar plot?
(6) What is an error bar?
(7) What is animation in Matplotlib?
(8) What is FuncAnimation()?
(9) What is an astroid?
(10) What is a spiral?
(11) What is a spirograph?
(12) What is the use of set_data()?
(13) What is interval in animation?
(14) What is color mapping in plots?

2.8.2 Short Answer Questions


(1) Explain how linspace() is used in plotting.
(2) Differentiate between arange() and linspace().
(3) Explain even and odd functions with examples.
(4) Why is plotting a circle difficult using Cartesian form?
(5) Explain parametric representation of a circle.
(6) What are error bars? Why are they important?
(7) Explain how animation is created in Matplotlib.
(8) What is the role of the update function in animation?
(9) Explain astroid with its parametric equations.
(10) Explain Archimedean spiral.
(11) What is a spirograph? Explain briefly.
(12) Explain the use of color in 2D plots.

2.8.3 Programming Questions


(1) Plot y = sin (x) for x ∈ [−π, π].
(2) Plot sin (x) and sin (x2 ) on the same graph.
(3) Write a program to plot a circle using Cartesian method.
(4) Write a program to plot a circle using parametric equations.

84 Government Victoria College


2.8. Exercises: Plotting Mathematical
Functions and Visualization Chapter 2. Data visualization

(5) Plot an Archimedean spiral.


(6) Plot an astroid using parametric equations.
(7) Write a program to draw a spirograph.
(8) Plot a graph with error bars.
(9) Create a simple animation of a moving sine wave.
(10) Write a program to generate a colored 2D plot.

2.8.4 MCQs
(a) Which function generates evenly spaced values?

(a) arange() (b) linspace() (c) random() (d) zeros()

(b) sin (x) is:

(a) even (b) odd (c) neither (d) constant

(c) Parametric circle uses:



(a) x = a + b (b) x = a cos t (c) x = t2 (d) x = t

(d) Which function is used for animation?

(a) animate() (b) (c) move() (d) repeat()


FuncAnimation()

(e) Error bars represent:

(a) exact values (b) uncertainty (c) color (d) speed

(f) Which curve uses x = a cos3 t?

(a) ellipse (b) astroid (c) spiral (d) circle

Answers: (b), (b), (b), (b), (b), (b)

2.8.5 Error Identification


(1) Identify the error:
x = np . linspace (0 ,1 ,10)

(2) Identify the error:


plt . plot (x , np . sin )

(3) Identify the error:


y = np . sqrt ( a **2 - x )

Government Victoria College 85


Chapter 2. Data visualization 2.9. 3D Plots

(4) Identify the error:


anim = FuncAnimation ( fig , update )

(5) Identify the error:


plt . errorbar (x , y )

2.8.6 Higher Order Questions


(1) Compare Cartesian, parametric and polar methods for plotting a circle.
(2) Explain the importance of visualization in understanding mathematical func-
tions.
(3) Describe how animation helps in understanding dynamic systems.
(4) Compare different famous curves with examples.
(5) Explain how color improves data visualization.

2.9 3D Plots
3D plots are used to visualize functions of two variables. The input variables are
represented on the x-axis and y-axis, and the function value is represented on the
z-axis.

2.9.1 Importing 3D Toolkit


To create 3D plots, we need to import the 3D toolkit from Matplotlib.
from mpl_toolkits . mplot3d import Axes3D

2.9.2 meshgrid()
In 3D plotting, we need values of a function z = f (x, y) for all combinations of x and
y.
The meshgrid() function is used to generate a grid of (x, y) coordinate pairs.
x = np . linspace ( -5 , 5 , 100)
y = np . linspace ( -5 , 5 , 100)

X , Y = np . meshgrid (x , y )

Explanation:

⋄ x and y are 1D arrays


⋄ meshgrid() converts them into 2D arrays
⋄ X contains x-coordinates repeated row-wise
⋄ Y contains y-coordinates repeated column-wise

86 Government Victoria College


2.9. 3D Plots Chapter 2. Data visualization

2.9.3 Computing Z Values

Z = X **2 + Y **2

Explanation:

⋄ Function is evaluated at each (x, y) pair


⋄ Result is a 2D array of z-values

2.9.4 Creating 3D Plot

fig = plt . figure ()


ax = fig . add_subplot ( projection = ’3d ’)

ax . plot_surface (X , Y , Z )

plt . show ()

2.9.5 Example Program

import numpy as np
import matplotlib . pyplot as plt
from mpl_toolkits . mplot3d import Axes3D

x = np . linspace ( -5 , 5 , 100)
y = np . linspace ( -5 , 5 , 100)

X , Y = np . meshgrid (x , y )
Z = X **2 + Y **2

fig = plt . figure ()


ax = fig . add_subplot ( projection = ’3d ’)

ax . plot_surface (X , Y , Z )

plt . show ()

2.9.6 Important Points


⋄ meshgrid() is essential for 3D plotting
⋄ It creates all possible (x, y) combinations
⋄ plot_surface() requires 2D arrays

2.9.7 Summary
⋄ meshgrid() converts 1D arrays into coordinate grid
⋄ 3D plots visualize z = f (x, y)

Government Victoria College 87


Chapter 2. Data visualization 2.9. 3D Plots

Figure 2.4. 3D plot of z = x2 + y 2 .

⋄ Surface plots represent height as the third dimension

88 Government Victoria College


MODULE III
CHAPTER 3
Symbolic Computation, SymPy

3.1 Introduction
Symbolic computation refers to the manipulation of mathematical expressions in a
symbolic form rather than using numerical approximations. Unlike numerical compu-
tation, which provides approximate values, symbolic computation gives exact results.
For example,
π
 
sin =1
2
is obtained exactly in symbolic computation, whereas numerical methods may only
give an approximate value.

3.1.1 SymPy
SymPy is a Python library designed for symbolic mathematics. It allows users to
perform algebraic manipulations, calculus operations, and equation solving in a manner
similar to traditional mathematical notation. It is especially useful in mathematics,
physics, and engineering applications.

3.1.2 Features of SymPy


SymPy provides several important features:

⋄ Creation of symbolic variables.


⋄ Algebraic manipulation such as expansion, factorization, and simplification.
⋄ Calculus operations including differentiation and integration.
⋄ Solving algebraic equations.
⋄ Pretty printing of mathematical expressions.

3.1.3 Symbolic vs Numerical Computation

Numerical Computation Symbolic Computation


Uses approximations Gives exact results
Uses floating-point numbers Uses symbols
Example: 3.1416 Example: π
Faster for large data Better for analysis
Chapter 3. Symbolic
Computation, SymPy 3.2. The SymPy Module

3.1.4 Typical Workflow in SymPy


The general steps in using SymPy are:

(1) Import the SymPy module.


(2) Define symbolic variables.
(3) Construct mathematical expressions.
(4) Apply operations such as simplification, differentiation, or integration.

3.1.5 Applications
Symbolic computation using SymPy is widely used in:

⋄ Solving algebraic equations


⋄ Calculus problems
⋄ Mathematical modelling
⋄ Physics and engineering analysis
⋄ Educational demonstrations

SymPy transforms Python into a powerful mathematical tool by enabling exact


symbolic computation, thereby bridging the gap between programming and mathe-
matics.

3.2 The SymPy Module


SymPy is a full featured computer algebra system (CAS) written in the Python pro-
gramming lan- guage. Since SymPy is available as a Python library, it is possible to
combine it with other packages like Numpy, Scipy etc. if required.

3.2.1 Importing SymPy


To use SymPy in a Python program, the module must first be imported. This can be
done in different ways:
import sympy as sp
The second method allows direct use of SymPy functions without prefixing them
with the module name.

3.2.2 Basic Usage


After importing SymPy, symbolic variables can be defined and used to construct ex-
pressions. For example:
import sympy as sp
x = [Link](’x’)
expr = x**2 + 2*x + 1
print(expr)

92 Government Victoria College


Chapter 3. Symbolic
3.3. Formatting the Output Computation, SymPy

This creates a symbolic expression instead of computing a numerical value.

3.2.3 Advantages of SymPy


⋄ Provides exact results instead of approximations.
⋄ Supports symbolic manipulation of algebraic expressions.
⋄ Useful for solving equations analytically.
⋄ Helps in performing calculus operations like differentiation and integration.
⋄ Produces readable mathematical output.

3.2.4 Applications
SymPy is widely used in:

⋄ Algebraic simplification
⋄ Solving equations
⋄ Calculus computations
⋄ Scientific and engineering problems

3.3 Formatting the Output


In SymPy, mathematical expressions can be displayed in a readable and visually ap-
pealing format. By default, expressions are printed in a simple text form, but SymPy
provides methods to improve the presentation of output.

3.3.1 Default Output


When a symbolic expression is printed using the print() function, it appears in plain
text form.

import sympy as sp
x = [Link](’x’)
expr = x**2 + 2*x + 1
print(expr)

Output:

x**2 + 2*x + 1

This kind of plain text output is supported by the Python Interpreter and all IDEs.
Under Jupyter Notebook, the equations are formatted better. For example the output
of the above statements under Jupyter Notebook is

x2 + 2x + 1

Government Victoria College 93


Chapter 3. Symbolic
Computation, SymPy 3.4. Simplification

3.4 Simplification
SymPy provides several functions to simplify algebraic expressions. Simplification
helps in rewriting expressions into a more compact or meaningful form. It is an es-
sential feature in symbolic computation, enabling easier interpretation and further
manipulation of expressions.

3.4.1 Basic Simplification


The simplify() function reduces an expression to its simplest form.
import sympy as sp
x = [Link](’x’)
expr = (x**2 + 2*x + 1)/(x + 1)
print([Link](expr))
Output:
x + 1

3.4.2 Expand
The expand() function multiplies out products and powers in an expression.
import sympy as sp
x, y = symbols(’x y’)
expr = (x + y)**2
print([Link](expr))
Output:
x**2 + 2*x*y + y**2
expand() can result in simplification due to cancellation.
import sympy as sp
x, y = symbols(’x’)
expr = (x + 1)*(x-2)-(x-1)*x
print([Link](expr))
Output:
-2

3.4.3 Factor
The factor() function expresses an expression as a product of simpler factors. It
convets a polynomial into it’s irreducible form.
expr = x**2 -y**2
[Link](expr)
Output:
(x + y)*(x-y)

94 Government Victoria College


Chapter 3. Symbolic
3.5. Calculus Computation, SymPy

3.4.4 Collect
The collect() function collects like terms with respect to a specified variable.
Example 1

expr = x*y+x-3+2*x**2*y**3-y**2*x**2+x**3*y**3
[Link](expr, x)

Output:

x**3y**3+x**2*(2*y**3-y**2)+x*(y+1)-3

Example 2

expr = x*y+x-3+2*x**2*y**3-y**2*x**2+x**3*y**3
[Link](expr, y)

Output:

-x**2y**2+x*y+x+y**3*(x**3+2*x**2)-3

3.4.5 Importance of Simplification


⋄ Reduces complexity of expressions.
⋄ Makes further computations easier.
⋄ Helps in identifying patterns such as factors or common terms.

3.5 Calculus
SymPy provides powerful tools for performing calculus operations symbolically. These
include differentiation, integration, and numerical evaluation of integrals. Symbolic
computation allows exact results, which is a major advantage over numerical methods.

3.5.1 Differentiation
Differentiation in SymPy is performed using the diff() function. It computes the
derivative of an expression with respect to a given variable.
Example
d  3 
x + 2x2 + x = 3x2 + 4x + 1
dx
import sympy as sp
x = [Link](’x’)
expr = x**3 + 2*x**2 + x
[Link](expr, x)

Output:

3*x**2+4*x+1

Government Victoria College 95


Chapter 3. Symbolic
Computation, SymPy 3.5. Calculus

3.5.2 Higher Order Derivatives


Higher order derivatives can be computed by specifying the order:
Esample
d2  3 
x + 2x 2
+ x = 6x + 4
dx2
expr=x**3 + 2*x**2 + x
[Link](expr, x, 2)
Output:
6*x + 4

3.5.3 Partial Derivatives (Multiple Variables)


For functions of more than one variable, SymPy computes partial derivatives.
Example
∂  2 
x y + y 3 = 2xy
∂x
x, y = [Link](’x y’)
f = x**2 * y + y**3
[Link](f, x)
Output:
2*x*y
Example
∂  2 
x y + y 3 = x2 + 3y 2
∂y
[Link](f, y)
Output:
x**2 + 3*y**2

3.5.4 Higher Order Partial Derivatives


SymPy also supports mixed partial derivatives.
Example
∂2  2 
x y + y 3 = 2x
∂y∂x
[Link](f, x, y)
∂2f
Output: This gives ∂y∂x

2*x
Example
∂ 2f
= 6y
∂y 2
diff(f, y, 2)

96 Government Victoria College


Chapter 3. Symbolic
3.5. Calculus Computation, SymPy

3.5.5 General Syntax


diff(expr, var, order)

⋄ expr : expression to differentiate


⋄ var : variable of differentiation
⋄ order : order of derivative (optional)

First derivative:

diff(expr, var)

Higher order derivative:

diff(expr, var, order)

Partial derivative:

diff(expr, var1)
diff(expr, var2)

Mixed derivative:

diff(expr, var1, var2)

Multiple Orders (Compact Form):

diff(expr, var1, order1, var2, order2)

3.5.6 Using Derivative Object and doit()


SymPy can represent derivatives symbolically using the Derivative object. The
Derivative() function gives an unevaluated derivative. The actual computation is
performed using doit().

import sympy as sp
x = [Link](’x’)
f = x**3 + 2*x**2 + x
g=[Link](f, x)
print(g)
print([Link]())

Output

Derivative(x**3 + 2*x**2 + x, x)
3*x**2 + 4*x + 1

Government Victoria College 97


Chapter 3. Symbolic
Computation, SymPy 3.5. Calculus

3.5.7 Integration
Integration is performed using the integrate() function.

Indefinite Integral:
integrate(expr, var)
Example
Z   x4 2x3 x2
x3 + 2x2 + x dx = + +
4 3 2
import sympy as sp
x = [Link](’x’)
expr = x**3 + 2*x**2 + x
[Link](expr, x)
Definite Integral:
integrate(expr, (var, lower_limit, upper_limit))
Example Z 1  1 2 1
x3 + 2x2 + x dx = + +
0 4 3 2
import sympy as sp
x = [Link](’x’)
expr = x**3 + 2*x**2 + x
[Link](expr, (x, 0, 1))

3.5.8 Numerical Integration


SymPy can compute numerical values using evalf().
integrate(expr, (var, lower_limit, upper_limit)).evalf(n)
This gives a decimal approximation of the definite integral correct to n decimal
places. Example Z 1  
x3 + 2x2 + x dx = 1.42
0
import sympy as sp
x = [Link](’x’)
expr = x**3 + 2*x**2 + x
[Link](expr, (x, 0, 1)).evalf(2)

3.5.9 Applications
Calculus operations in SymPy are useful in:

⋄ Finding derivatives and integrals analytically


⋄ Solving mathematical problems in physics and engineering
⋄ Verifying manual calculations
⋄ Educational demonstrations

98 Government Victoria College


Chapter 3. Symbolic
3.6. Excercise Computation, SymPy

3.6 Excercise
3.6.1 Very Short Answer
(1) What is symbolic computation?
(2) What is SymPy?
(3) What is the use of expand()?
(4) What is diff()?
(5) What is a symbol in SymPy?
(6) Write the command to define a variable x.
(7) What is the use of factor()?
(8) What does collect() do?
(9) Write a command to differentiate x2 .
(10) Write a command to integrate x2 .
(11) What is evalf() used for?
(12) What is the difference between diff() and Derivative()?

3.6.2 Short Answer


(1) Explain symbolic computation with an example.
(2) Differentiate between numerical and symbolic computation.
(3) Explain how to define symbols in SymPy.
(4) Explain expand() with example.
(5) Explain factor() with example.
(6) Explain collect() with example.
(7) Write syntax of diff() with example.
(8) Write syntax of integrate() with example.

3.6.3 Long Answer


(1) Explain SymPy module and its features.
(2) Explain simplification functions in SymPy.
(3) Compare expand(), factor() and collect().
(4) Explain calculus operations in SymPy.
(5) Explain formatting output.
(6) Explain differentiation in SymPy including higher order derivatives.
(7) Explain partial derivatives with example.
(8) Explain integration (definite and indefinite) in SymPy.

3.6.4 Programming

(1) Write a program to expand (x + 1)3


(2) Write a program to factor x2 + 2x + 1.

Government Victoria College 99


Chapter 3. Symbolic
Computation, SymPy 3.6. Excercise

(3) Differentiate x3 + 2x2 + x using Sympy.


(4) Find second derivative of x4 using Sympy.
(5) Find partial derivatives of all orders of x2 y + y 3 using Sympy.
(6) Differentiate x3 + 2x2 using Sympy.
(7) Integrate x2 using Sympy.

100 Government Victoria College


CHAPTER 4
Introduction to Pandas

4.1 Introduction
Pandas is designed for working with tabular or heterogeneous data, like contents of a
spreadsheet.

4.2 Series
A Series is a one-dimensional labeled array provided by the Pandas library. It can
store elements of any data type such as integers, floats, or strings. Each element in
a Series is associated with a label called an index. If not specified it takes integers
ranging from 0 to N − 1 as indeces for a series of length N by default.

4.2.1 Creating a Series


A Series can be created using the Series() function.

[Link] Series from List


import pandas as pd
s = [Link]([10, 20, 30, 40])
By default, the index starts from 0. Thus
s[0] = 10, s[1] = 20, s[2] = 30, and s[3] = 40.

[Link] Series with Custom Index


We can specify custom labels using the index argument.
s = [Link]([10, 20, 30, 40], index=[’a’, ’b’, ’c’, ’d’])
In this case
s[’a’]=10, s[’b’]=20, s[’c’]=30, and s[’d’]=40.
Pandas Index can contain duplicate labels.
import pandas as pd
t = [Link]([4, 7, -5, 3], index=[’d’, ’a’, ’a’, ’c’])
print(t[’a’])
Chapter 4. Introduction to Pandas 4.2. Series

Output
a 7
a -5
It can be seen that the index ’a’ is appearing twice. Pandas supports non-unique index
values. If an operation that does not support duplicate index values is attempted, an
exception will be raised at that time.

4.2.2 Accessing Elements


Elements of a Series can be accessed using their index.

s[’a’]
s[0]

4.2.3 Series from Dictionary


A Series can also be created from a dictionary, where keys become indices.

data = {’a’: 1, ’b’: 2, ’c’: 3}


s = [Link](data)

[Link] Altering Indices of a Series


The indices of a Series can be changed using the .index attribute or the .reindex()
method.

Using .index attribute


Example:

ser = [Link]([10, 20])

The indices are 0 and 1.

[Link] = [’a’, ’b’]

The indices 0 and 1 are replaced by ’a’ and ’b’ respectively.

Using .reindex() method


It is possible to reindex a Series. This may also change the number of indices. The
relation between an index and its corresponding value is preserved during this opera-
tion. This is achieved using the .reindex() method.

Example:
import pandas as pd
ser = [Link]([10, 20], index=[’a’, ’b’])
ser = [Link]([’b’, 1, 2])
print(ser)

102 Government Victoria College


4.2. Series Chapter 4. Introduction to Pandas

Output:
b 20.0
1 NaN
2 NaN
dtype: float64
It can be seen that the value corresponding to the old index ’b’ is preserved. The
data corresponding to the index ’a’ is lost. The new indices 1 and 2 are assigned NaN
(Not a Number) values.

4.2.4 Operations on Series


Basic arithmetic operations can be performed on Series. operations between Series
automatically align the data based on index.
s + 2
s * 3
These operations add 2 to each element of s and multiply each element of s by 3.
The default result of operations between differently indexed objects yields the union
of the indices in order to avoid loss of information.
When a mathematical operation is performed between two Series, the elements
with the same indices are operated upon and the result is stored with the same index,
while all other indices are retained with the value NaN.

4.2.5 .dropna() Method


The indices with missing data can be removed using the .dropna() method.

Example
import pandas as pd
s1 = [Link]([10, 20, 30, 40], index=[0, 1, 2, 3])
s2 = [Link]([12, 13, 14], index=[1, 2, 3])
s = s1 * s2
print(s)
print([Link]())
Output:
0 NaN
1 240.0
2 390.0
3 560.0
dtype: float64

1 240.0
2 390.0
3 560.0
dtype: float64

Government Victoria College 103


Chapter 4. Introduction to Pandas 4.2. Series

4.2.6 Name Attribute


Both the Series object and its index have a name attribute.

Example
import pandas as pd
s = [Link]([34, 56], index=[’John’, ’Ravi’], name=’ages’)
[Link] = ’names’
print([Link])
print([Link])

Output:

ages
names

4.2.7 Properties of a Series


⋄ A one-dimensional labeled data structure
⋄ Can store data of various types (integers, floats, strings, etc.)
⋄ Each element is associated with an index (label)
⋄ Allows duplicate indices
⋄ Supports vectorized operations

4.2.8 Exercise
[Link] Very Short Answer
(1) What is a Series in Pandas?
(2) What is an index in a Series?
(3) Write the syntax to create a Series.
(4) How can a Series be created from a list?
(5) How can a Series be created from a dictionary?
(6) What is the default index of a Series?
(7) What is the use of the index attribute?
(8) What is index alignment?
(9) What does reindex() do?
(10) What is NaN?
(11) What does dropna() do?
(12) What is the use of the name attribute?
(13) Can a Series have duplicate indices?

[Link] Short Answer


(1) Explain the structure of a Series.

104 Government Victoria College


4.2. Series Chapter 4. Introduction to Pandas

(2) How is Series different from a list?


(3) How do you create a Series with custom indices?
(4) Explain how to access elements in a Series.
(5) Explain the difference between default index and custom index.
(6) Explain reindexing with an example.
(7) What happens when new indices are introduced using reindex()?
(8) Explain the use of dropna() with example.
(9) Explain the name attribute of a Series and its index.
(10) Explain operations between two Series with different indices.
(11) How does Pandas handle missing values in Series operations?

[Link] Long Answer


(1) Explain the Series data structure in Pandas with examples.
(2) Explain different ways to create a Series.
(3) Explain reindexing of a Series and its effects.
(4) Explain handling of missing values in Series.
(5) Explain arithmetic operations between two Series.
(6) Explain properties of a Series.

[Link] Programming Questions


(1) Write a program to create a Series from a list.
(2) Write a program to create a Series with custom indices.
(3) Write a program to create a Series from a dictionary.
(4) Write a program to access elements of a Series.
(5) Write a program to change indices using .index.
(6) Write a program to reindex a Series.
(7) Write a program to demonstrate missing values in Series.
(8) Write a program to remove missing values using dropna().
(9) Write a program to assign a name to a Series and its index.
(10) Write a program to perform arithmetic operations on two Series.

[Link] Output-Based Questions


(1) Find the output of:

s = [Link]([10, 20, 30])


print(s)

(2) Find the output of:

Government Victoria College 105


Chapter 4. Introduction to Pandas 4.3. DataFrame

s = [Link]([10, 20, 30], index=[’a’, ’b’, ’c’])


print(s[’b’])

(3) Find the output of:

s = [Link]([10, 20], index=[’a’, ’b’])


s = [Link]([’b’, ’c’])
print(s)

(4) Find the output of:

s1 = [Link]([1, 2], index=[’a’, ’b’])


s2 = [Link]([3, 4], index=[’b’, ’c’])
print(s1 + s2)

[Link] Conceptual Questions


(1) Why is Series considered a labeled array?
(2) Explain how index alignment works in Series.
(3) What is the importance of NaN in Pandas?
(4) Explain how Pandas avoids loss of information during operations.
(5) Why does reindexing introduce NaN values?

4.3 DataFrame
A DataFrame represents a tabular, spreadsheet-like data structure containing an or-
dered collection of columns, each of which can be of a different data type. It has both
row and column indices.
A DataFrame can be considered as a more flexible version of a two-dimensional
array. Unlike a NumPy 2D array, the data need not be of the same type, and the row
and column indices are not restricted to the range 0 to N − 1.
DataFrames can be created in several different ways.

4.3.1 DataFrame from a Numpy array


Let arr be a NumPy array of dimension m × n. Let cols be a list of length n and
rows be a list of length m. A DataFrame with data from the array arr, whose column
indices are taken from the list cols and whose row indices are taken from the list rows,
can be created using the statement:

df = [Link](arr, columns=cols, index=rows)

106 Government Victoria College


4.3. DataFrame Chapter 4. Introduction to Pandas

Example
import numpy as np
import pandas as pd
data = [Link](12).reshape(3,4)
df = [Link](data, columns=["A", "B", "C", "D"], index = [’a’,’b’,’c’])
print(df)
Output
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11

4.3.2 DataFrame from a Dictionary of Pandas Series


If we have a dictionary dcts of Pandas Series, then a DataFrame can be created using
the statement:
df = [Link](dcts)

Example
import numpy as np
import pandas as pd
s1 = [Link]([1.0, 2.0, 3.0], index=["a", "b", "c"])
s2 = [Link]([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"])
d = {"one": s1, "two": s2}
df = [Link](d)
print(df)
Output:
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
Each column is formed from a Series, where the dictionary keys become the column
names. The union of all the Series indices forms the DataFrame index. If any Series is
missing a particular index, the corresponding value is assigned NaN. The data is aligned
based on the index values.
Note: When creating a DataFrame from a dictionary of Series, Pandas automatically
aligns data based on index labels.

4.3.3 DataFrame from a Dictionary of Lists


If we have a dictionary dctl of lists (or arrays), then a DataFrame can be created
using:
df = [Link](dctl)

Government Victoria College 107


Chapter 4. Introduction to Pandas 4.3. DataFrame

Example
import numpy as np
import pandas as pd
d = {"one": [1.0, 2.0, 3.0, 4.0], "two": [4.0, 3.0, 2.0, 1.0]}
df = [Link](d, index=[’a’, ’b’, ’c’, ’d’])
print(df)

Output:

one two
a 1.0 4.0
b 2.0 3.0
c 3.0 2.0
d 4.0 1.0

The number of elements in each list or array in the dictionary must match the
number of elements in the index list. Each dictionary key becomes a column label,
and its corresponding values form the column entries.

4.3.4 Saving DataFrames to CSV Files


If we have a DataFrame df, it can be saved to a CSV file [Link] using:

df.to_csv(’[Link]’)

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [’a’,’b’,’c’,’d’,’e’]
[Link] = ’I’
df.to_csv(’[Link]’)

The contents of the file [Link] will be:

I,A,B,C,D
a,0,1,2,3
b,4,5,6,7
c,8,9,10,11
d,12,13,14,15
e,16,17,18,19

4.3.5 Reading DataFrames from CSV Files


A DataFrame can be read from a CSV file [Link] using:

df = pd.read_csv(’[Link]’)
print(df)

108 Government Victoria College


4.3. DataFrame Chapter 4. Introduction to Pandas

Example
import pandas as pd
df = pd.read_csv(’[Link]’)
print(df)

Output:

I A B C D
0 a 0 1 2 3
1 b 4 5 6 7
2 c 8 9 10 11
3 d 12 13 14 15
4 e 16 17 18 19

It can be seen that a new default index column has been created. This can be
avoided by specifying the index column using the index_col parameter in pd.read_csv().

Example
import pandas as pd
df = pd.read_csv(’[Link]’, index_col=’I’)
print(df)

Output:

I A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
e 16 17 18 19

Note: By default, read_csv() assigns a new integer index. To use an existing column
as index, specify index_col.

4.3.6 Index and Column Properties


A Pandas DataFrame allows identical names for more than one column. The same is
true for row indices as well. The index also has a name attribute.

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "A", "C", "D"])
[Link] = [1, 2, 2, 3, 4]
[Link] = ’I’
print(df)

Government Victoria College 109


Chapter 4. Introduction to Pandas 4.3. DataFrame

Output:

A A C D
I
1 0 1 2 3
2 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19

Note: Pandas allows duplicate column names and index values, but this may lead to
ambiguity in data access.

4.3.7 Column Operations


[Link] Selecting a Column
A particular column with column name ’A’ of a DataFrame df can be selected by

df[’A’]

or by

df.A

Note: The method df.A works only when the column name is a valid Python iden-
tifier and does not contain spaces or special characters. The recommended method is
df[’A’].
More than one column can be selected by passing the required column names in a
list.

df[’A’,’B’]

[Link] Applying Conditions


Whether the elements of a particular column of a DataFrame satisfy a condition can
be checked by applying the condition to that column.

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
print(df[’A’] > 7)

Output:

110 Government Victoria College


4.3. DataFrame Chapter 4. Introduction to Pandas

I
1 False
2 False
3 True
4 True
5 True
Name: A, dtype: bool

The DataFrame can be filtered using the given condition.

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
print(df[df[’A’] > 7])

Output:

A B C D
I
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19

The same result can also be obtained using:

print([Link](’A > 7’))

[Link] Adding Columns


New columns can be added to an existing DataFrame using:

df[’column_name’] = list_of_values

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
df[’E’] = df.A + df.B # df.E cannot be used on the left side
df[’G’] = [11, 12, 13, 14, 15]
print(df)

Output:

Government Victoria College 111


Chapter 4. Introduction to Pandas 4.3. DataFrame

A B C D E G
I
1 0 1 2 3 1 11
2 4 5 6 7 9 12
3 8 9 10 11 17 13
4 12 13 14 15 25 14
5 16 17 18 19 33 15

New columns can also be created using the assign() function without modifying
the existing DataFrame.

ndf = [Link](newcolumn=data)

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
ndf = [Link](E=[11, 12, 13, 14, 15])
print(ndf)

Output:

A B C D E
I
1 0 1 2 3 11
2 4 5 6 7 12
3 8 9 10 11 13
4 12 13 14 15 14
5 16 17 18 19 15

[Link] Deleting/Extracting Columns


A column can be deleted from an existing DataFrame using:

del df[’column_name’]

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
del df[’A’]
print(df)

112 Government Victoria College


4.3. DataFrame Chapter 4. Introduction to Pandas

Output:

B C D
I
1 1 2 3
2 5 6 7
3 9 10 11
4 13 14 15
5 17 18 19

A column can be extracted as a Pandas Series from an existing DataFrame using:

s = [Link](’column_name’)

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [1, 2, 3, 4, 5]
[Link] = ’I’
s = [Link](’A’)
print(s)

Output:

I
1 0
2 4
3 8
4 12
5 16
Name: A, dtype: int64

4.3.8 Indexing and Slicing Rows


Accessing Rows
Rows of a DataFrame can be accessed using their labels (names) or their integer
positions.
If we use row labels, the .loc[] method is used. If we access rows by their integer
positions, the .iloc[] method is used.

[Link][’row_name’]
[Link][row_number]

Government Victoria College 113


Chapter 4. Introduction to Pandas 4.3. DataFrame

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [’a’, ’b’, ’c’, ’d’, ’e’]
[Link] = ’I’
sn = [Link][’a’]
s1=[Link][0]
print(sn)
print(s1)

Output:

A 0
B 1
C 2
D 3
Name: a, dtype: int64
A 0
B 1
C 2
D 3
Name: a, dtype: int64

[Link] Applying Conditions


Whether the elements of a particular column of a DataFrame satisfy a condition can
be checked by applying the condition to that column.

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [’a’, ’b’, ’c’, ’d’, ’e’]
[Link] = ’I’
print([Link][’a’] > 1)

Output:

A False
B False
C True
D True
Name: a, dtype: bool

The DataFrame can be filtered using the given condition.

114 Government Victoria College


4.3. DataFrame Chapter 4. Introduction to Pandas

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [’a’, ’b’, ’c’, ’d’, ’e’]
[Link] = ’I’
print([Link][:, [Link][’a’] >1])

Output:

C D
I
a 2 3
b 6 7
c 10 11
d 14 15
e 18 19

4.3.9 Adding a Row


A new row can be added to a DataFrame using:

[Link][’row_name’] = data

Example
import numpy as np
import pandas as pd
df = [Link]([Link](20).reshape(5,4), columns=["A", "B", "C", "D"])
[Link] = [’a’, ’b’, ’c’, ’d’, ’e’]
[Link] = ’I’
[Link][’f’] = [10, 20, 30, 40]
print(df)

Output:

A B C D
I
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
e 16 17 18 19
f 10 20 30 40

Government Victoria College 115


Chapter 4. Introduction to Pandas 4.4. Concatenating DataFrames

4.4 Concatenating DataFrames


The concat() function is used to concatenate multiple Series or DataFrame objects
along a particular axis.

df = [Link]([df1, df2], axis=axis_value, sort=False)

Here, axis=0 denotes concatenation along rows (default), and axis=1 denotes con-
catenation along columns.

Example
import numpy as np
import pandas as pd
d1 = [Link](6).reshape(2,3)
d2 = [Link](100,106).reshape(2,3)
df1 = [Link](d1, columns=["A", "B", "C"], index = [’a’,’b’])
df2 = [Link](d2, columns=["D", "B", "F"], index = [’b’,’c’])
dfr = [Link]([df1,df2], axis=0, sort =False)
dfc = [Link]([df1,df2], axis=1, sort =False)
print(dfr)
print(dfc)

Output:

A B C D F
a 0.0 1 2.0 NaN NaN
b 3.0 4 5.0 NaN NaN
b NaN 101 NaN 100.0 102.0
c NaN 104 NaN 103.0 105.0

A B C D B F
a 0.0 1.0 2.0 NaN NaN NaN
b 3.0 4.0 5.0 100.0 101.0 102.0
c NaN NaN NaN 103.0 104.0 105.0

When axis=0, the DataFrames are concatenated row-wise such that columns with
the same names are aligned. When axis=1, the DataFrames are concatenated column-
wise such that rows with the same index labels are aligned. Wherever data is missing,
the corresponding entries are filled with NaN.

4.4.1 Arithmetic of DataFrames


An operation between two DataFrames results in a new DataFrame whose row indices
are the union of the row labels of the operands and whose column indices are the union
of the column labels of the operands. The operation is carried out on elements with
matching row and column labels, and entries corresponding to non-matching labels are
assigned NaN. The dimensions of the operands need not be the same.

116 Government Victoria College


4.4. Concatenating DataFrames Chapter 4. Introduction to Pandas

Illustrative Example
import pandas as pd

df1 = [Link]({’A’:[1,2], ’B’:[3,4]}, index=[’x’,’y’])


df2 = [Link]({’B’:[5,6], ’C’:[7,8]}, index=[’y’,’z’])

print(df1)
print(df2)
print(df1 + df2)

Output:

df1:
A B
x 1 3
y 2 4

df2:
B C
y 5 7
z 6 8

df1 + df2:
A B C
x NaN NaN NaN
y NaN 9.0 NaN
z NaN NaN NaN

Explanation:

⋄ Row indices: {x, y, z} (union of indices)


⋄ Column indices: {A, B, C} (union of columns)
⋄ Only matching position is (y, B):

4+5=9

⋄ All other positions are filled with NaN since corresponding elements are missing.

4.4.2 Excercise
[Link] Very Short Answer
(1) What is a DataFrame in Pandas?
(2) What are row and column indices?
(3) How is a DataFrame different from a Series?
(4) Write the syntax to create a DataFrame from a NumPy array.

Government Victoria College 117


Chapter 4. Introduction to Pandas 4.4. Concatenating DataFrames

(5) Write the syntax to create a DataFrame from a dictionary.


(6) What is the use of columns parameter in DataFrame creation?
(7) What is the use of index parameter?
(8) What does to_csv() do?
(9) What does read_csv() do?
(10) What is index_col in read_csv()?
(11) Can a DataFrame have duplicate column names?
(12) What is the use of concat()?
(13) What is index alignment?
(14) What is the difference between del and pop()?

[Link] Short Answer


(1) What is NaN?
(2) Explain the structure of a DataFrame.
(3) How is DataFrame different from a NumPy array?
(4) Explain how to create a DataFrame from a NumPy array.
(5) Explain how to create a DataFrame from a dictionary of Series.
(6) Explain how to create a DataFrame from a dictionary of lists.
(7) Explain how to save a DataFrame to a CSV file.
(8) Explain how to read a DataFrame from a CSV file.
(9) What happens if index_col is not specified?
(10) Explain duplicate indices and column names.
(11) Explain column selection in a DataFrame.
(12) Explain row selection using loc[] and iloc[].
(13) Explain how to add a new column.
(14) Explain how to add a new row.
(15) Explain how to delete a column.
(16) Explain the pop() method.

[Link] Long Answer


(1) Explain DataFrame with its properties and structure.
(2) Explain different methods of creating a DataFrame with examples.
(3) Explain reading and writing DataFrames to CSV files.
(4) Explain column operations in a DataFrame.
(5) Explain row operations in a DataFrame.
(6) Explain concatenation of DataFrames with examples.
(7) Explain arithmetic operations between DataFrames.
(8) Explain handling of missing values in DataFrames.

118 Government Victoria College


4.4. Concatenating DataFrames Chapter 4. Introduction to Pandas

[Link] Programming Questions


(1) Write a program to create a DataFrame from a NumPy array.
(2) Write a program to create a DataFrame from a dictionary of Series.
(3) Write a program to create a DataFrame from a dictionary of lists.
(4) Write a program to save a DataFrame to a CSV file.
(5) Write a program to read a DataFrame from a CSV file.
(6) Write a program to select a column from a DataFrame.
(7) Write a program to filter rows based on a condition.
(8) Write a program to add a new column.
(9) Write a program to add a new row.
(10) Write a program to delete a column.
(11) Write a program to extract a column using pop().
(12) Write a program to concatenate two DataFrames.
(13) Write a program to perform arithmetic operations on DataFrames.

[Link] Output-Based Questions


(1) Find the output of:

df = [Link]([[1,2],[3,4]], columns=[’A’,’B’])
print(df[’A’])

(2) Find the output of:

df = [Link]([[1,2],[3,4]], columns=[’A’,’B’])
df[’C’] = df[’A’] + df[’B’]
print(df)

(3) Find the output of:

df = [Link]([[1,2],[3,4]], columns=[’A’,’B’])
del df[’A’]
print(df)

(4) Find the output of:

df1 = [Link]({’A’:[1,2]}, index=[’x’,’y’])


df2 = [Link]({’A’:[3,4]}, index=[’y’,’z’])
print(df1 + df2)

Government Victoria College 119


Chapter 4. Introduction to Pandas 4.4. Concatenating DataFrames

(5) Find the output of:

df = [Link]([[1,2],[3,4]], columns=[’A’,’B’])
[Link][’c’] = [5,6]
print(df)

[Link] Conceptual Questions


(1) Why is a DataFrame considered a flexible data structure?
(2) Explain index alignment in DataFrames.
(3) Why does Pandas introduce NaN values?
(4) Explain the role of axis in concat().
(5) Explain the difference between loc[] and iloc[].
(6) Why must the length of data match the number of columns when adding a row?

120 Government Victoria College


MODULE IV
CHAPTER 5
Welcome to Sage!

5.1 Introduction
Sage can be used as a simple calculator to perform arithmetic and more advanced
mathematical computations. Expressions are entered and evaluated using the Evalu-
ate button or by pressing Shift + Enter.

5.2 Basic Arithmetic Operations


Operation Symbol in Sage
Addition +
Subtraction -
Multiplication *
Division /

Example:
2+3=5

5.3 Simple Interest Example


The formula for simple interest is:

A = P (1 + rt)

Sage Input:
900*(1+0.06*(90/365))

Click Evaluate.
Output:
913.315068493151

5.4 Exponents in Sage


Exponents can be written using:
Chapter 5. Welcome to Sage! 5.5. Important Syntax Rules

⋄ Caret: ˆ
⋄ Double asterisk: **

Example:

11000*(1+0.12)^3

15454.2080000000

5.5 Important Syntax Rules


5.5.1 No Commas in Numbers
⋄ Correct: 11000
⋄ Incorrect: 11,000

5.5.2 Explicit Multiplication


⋄ Correct: 11000*x
⋄ Incorrect: 11000x

5.5.3 Matching Parentheses


Every opening parenthesis must have a corresponding closing parenthesis.

5.6 Grouping Expressions


Always use parentheses for grouping.
Example:

550*(1-(1+0.05)^(-30))/0.05

Brackets [ ] and braces { } are not used for grouping expressions in Sage.

5.7 Editing Errors


Errors can be corrected by modifying the input and re-evaluating.

5.8 Common Mistakes


Most common errors include:

124 Government Victoria College


5.9. Key Points Chapter 5. Welcome to Sage!

(1) Missing multiplication symbol (*)


Writing 11000x + 1200 instead of 11000*x + 1200
(2) Using commas in numbers
Writing 11,000 instead of 11000
(3) Mismatched parentheses
Using incorrect brackets:

550 [ 1 - (1+0.05)^(-30) ]/0.05

or missing parentheses:

550 ( 1 - (1+0.05)^(-30 )/0.05

5.9 Key Points


⋄ Sage works like a programming-based calculator.
⋄ Syntax must be strictly followed.
⋄ It can handle both simple and complex computations.

5.10 Using Sage with Common Functions


5.10.1 Built-in Mathematical Functions
Sage provides several built-in mathematical functions such as square roots, logarithms,
exponentials, and constants like π and e.

5.10.2 Square Roots


Example:
sqrt(144)
= 12
Sage prefers exact values:
sqrt(8)

=2 2

which is the exact value of 8.
To obtain a decimal approximation, we use the N() function:
N(sqrt(8))

Government Victoria College 125


5.10. Using Sage with Common
Chapter 5. Welcome to Sage! Functions

2.82842712474619
If a decimal is used:

sqrt(3.4)

1.84390889145858

5.10.3 N() Function


The N() function will convert what is inside the parentheses to a real number, if
possible. If the argument expression is not an integer, it returns an approximate value
of the argument.
Either of N() or n() can be used. This function name is not case sensitive.

Example
N(2/3)
0.666666666666667

5.10.4 Numerical Approximation using N()


In N(), the precision of approximation can be specified in two ways:

N(expression, prec = binary precision in bits)


N(expression, digits = number of decimal digits)

Example
N(pi, prec=20)
3.1416

N(pi, digits=20)
3.1415926535897932385

Another function with the same pupose is

numerical_approx(expression, prec = binary precision in bits)


numerical_approx(expression, digits=no of digits)

5.10.5 Higher Order Roots


Higher roots can be computed using exponents:
6th root of 64 is found by

64^(1/6)
2

126 Government Victoria College


5.10. Using Sage with Common
Functions Chapter 5. Welcome to Sage!

5.10.6 Special Constants


⋄ π is written as pi
⋄ e is written as e

Lower case letters are used in both the cases.


High precision values:
numerical_approx(pi, digits=200)
or
N(sqrt(2), prec=200)

5.10.7 Tab Completion


Press the Tab key to auto-complete commands or view suggestions.

5.10.8 Case Sensitivity


Sage is case-sensitive:

⋄ sin ̸= Sin
⋄ pi ̸= Pi

Only exceptions include:

⋄ i or I (imaginary unit)
⋄ n() or N()
⋄ true/false and True/False

5.10.9 Exponentials
The exponential is written as
e^t
exp(t)
N(e^t)
or as
N(exp(t))
for decimal form.
Example:
exp(5*11+8)
e^3
Decimal form:
N(e^3)

Government Victoria College 127


5.10. Using Sage with Common
Chapter 5. Welcome to Sage! Functions

5.10.10 Logarithms
The function
log(number, base)
calculates the logarithm of a given number to the given base. The second arguemnet
base takes the value e by default and is optional. To find the logarithm of any number
to any base other than e, we have to mention the base argument.
Natural logarithm: log(100) # 2*log(10)
Common logarithm (base 10): log(90,10) # log(90)/log(10)
Binary logarithm (base 2): log(100,2) # 2*log(10)/log(2)
General base: log(100,42) # 2*log(10)/log(42)

To get the results in Decimal we have to use the N() function.


N(log(100)) #4.60517018598809

Example 5.10.1: Financial Application


Suppose you deposit $ 5000 in an account that earns 4.5% compounded monthly.
When will your total will reach $7000.
Answer We have,
A = P (1 + i)n
log A = log P + n log (1 + i)
log A − log P
n=
log (1 + i)
log 7000 − log 5000
=  
log 1 + 0.045
12

In SageMath, we calculate
N((log(7000)-log(5000))/log(1+0.045/12))
89.8940609330798
Hence, approximately 90 months (7 years 6 months). □

5.10.11 Square Roots (Advanced)


To find all roots we use the sqrt() function as
sqrt(number, all=True)

Example
sqrt(4, all=True)

[2, −2]

128 Government Victoria College


5.11. Using Sage for Trigonometry Chapter 5. Welcome to Sage!

5.10.12 Complex Numbers


SageMath can handle complex numbers. The complex number i is denoted by i or by
I.
Example:

sqrt(-4, all=True)

[2I, −2I]

Here I = −1.

5.10.13 Key Points


⋄ Sage prefers exact results.
⋄ Use N() for numerical approximations.
⋄ log() gives natural logarithm by default.
⋄ Supports high precision computations.
⋄ Handles complex numbers naturally.

5.11 Using Sage for Trigonometry


Sage provides built-in support for trigonometric functions such as sine, cosine, tangent,
cosecant, secant and cotangent . The syntax is straightforward and closely follows
standard mathematical notation.

5.11.1 Basic Trigonometric Functions


The common trigonometric functions are written as:

sin(x), cos(x), tan(x), csc(x), sec(x), cot(x)

Example:

sin(pi/3)
1/2*sqrt(3)

Sage returns exact values whenever possible. For decimal answers we use N()
function.

5.11.2 Working in Radians


Sage uses radians by default. Therefore, angles must be expressed in terms of π.

⋄ π/2 represents 90◦


⋄ π/3 represents 60◦

Government Victoria College 129


Chapter 5. Welcome to Sage! 5.11. Using Sage for Trigonometry

5.11.3 Decimal Approximations


To obtain a decimal value, use the N() function.

N(cos(pi/12))

0.965925826289

5.11.4 Undefined Values


Sage correctly handles undefined trigonometric values.

tan(pi/2)

Infinity

5.11.5 Reciprocal Trigonometric Functions


The reciprocal functions of sin(x), cos(x) and tan(x) are also available as:

csc(x), sec(x), cot(x)

5.11.6 Inverse Trigonometric Functions


Inverse trigonometric functions are written as:

arcsin(x), arccos(x), arctan(x)

Examples:

arcsin(1/2)
1/6*pi

arccos(1/2)
1/3*pi

5.11.7 Alternative Notation


Sage also accepts shorter forms:

Function Alternative
arcsin(x) asin(x)
arccos(x) acos(x)
arctan(x) atan(x)
arccot(x) acot(x)
arcsec(x) asec(x)
arccsc(x) acsc(x)

130 Government Victoria College


5.12. Matrices and Sage Chapter 5. Welcome to Sage!

5.11.8 Important Notes


⋄ Sage uses radians, not degrees.
⋄ Exact values are returned whenever possible.
⋄ Use N() for numerical approximations.
⋄ Trigonometric and inverse functions follow standard notation.

5.12 Matrices and Sage


SageMath handles matrices using Python-based syntax and structures, as it is built
on Python, though it extends Python with additional mathematical functionality.

A matrix in SageMath is represented as a list of lists, where each inner list cor-
responds to a row of the matrix. The element aij of a matrix A is accessed using
A[i-1][j-1].
Example:
The matrix
−1 2 1 −5 6
 
 0 0 −1 1 −5
B= 
 1 3 3 −1 0 
 

−1 5 −1 0 −1
can be defined in SageMath as:

B = matrix([
[-1, 2, 1, -5, 6],
[0, 0, -1, 1, -5],
[1, 3, 3, -1, 0],
[-1, 5, -1, 0, -1]
])

A matrix in SageMath can also be defined by specifying the number of rows and
columns along with a list of elements. The elements are filled row-wise into the matrix.
Syntax:

B = matrix(rows, columns, list_of_elements)

Example:

B = matrix(4, 5, [
-1, 2, 1, -5, 6,
0, 0, -1, 1, -5,
1, 3, 3, -1, 0,
-1, 5, -1, 0, -1
])

Government Victoria College 131


Chapter 5. Welcome to Sage! 5.12. Matrices and Sage

5.12.1 Row Reduces Echelon Form of a Matrix (RREF)


In SageMath, the row-reduced echelon form (RREF) of a matrix A can be computed
using the method [Link](). This method returns a new matrix that is row-equivalent
to A and is in reduced echelon form.
Example:

A = matrix([[1, 2, 3],
[2, 4, 6],
[1, 1, 1]])
B=[Link]()
print(B)

# B=[ [ 1 0 -1]
[ 0 1 2]
[ 0 0 0] ]

Example: Using Sage, solve the following linear system of equations

3481x + 59y + z = 0.87


6241x + 79y + z = 0.61
9801x + 99y + z = 0.42

The given system can be written as AX = B where

3481 59 1 0.87
     
x
A = 6241 79 1 , B = 0.61 , X = y  .
     

9801 99 1 0.42 z

The augmented matrix is

3481 59 1 0.87
 

Ab = 6241 79 1 0.61
 

9801 99 1 0.42

In SageMath,

Ab=[3,4],[3481,59,1,0.87,6241,0.79,1,0.61,9801,99,1,0.42]
C=[Link]()
print(C)

#C=[1.00000000000000 0.000000000000000 0.000000000000000 0.0000875000000000000]


[0.000000000000000 1.00000000000000 0.000000000000000 -0.0250750000000000]
[0.000000000000000 0.000000000000000 1.00000000000000 2.04483750000000]

Hence the solution is x = 0.0000875000000000000, y = −0.0250750000000000, z =


2.04483750000000.

132 Government Victoria College


5.13. Using Sage to Manipulate
Polynomials Chapter 5. Welcome to Sage!

5.13 Using Sage to Manipulate Polynomials


SageMath supports a wide range of operations on polynomials, including addition,
subtraction, multiplication, and division. It also provides several built-in methods for
simplifying and analyzing polynomials, such as .expand() for expanding expressions,
.factor() for factorization, and gcd() for computing the greatest common divisor of
polynomials.
Example:
a(x) = (x + 1)^2
b(x) = x^2 - 1
[Link]()
[Link]()
gcd(a(x), b(x))

5.14 Exercise
5.14.1 Short Answer
(1) Evaluate 2 + 3 using Sage.
(2) Write the Sage expression for 11000 (1 + 0.12)3 .

(3) Find 144.

(4) Convert 2 into decimal form.
(5) Evaluate log (100, 10).
(6) Compute sin (π/3).
(7) Convert π/3 radians to degrees.
(8) Define a 2 × 2 matrix in Sage.
(9) What is the command to compute RREF of a matrix?
(10) Expand (x + 1)2 .

5.14.2 Long Answer


(1) Explain the use of arithmetic operators in Sage with examples.
(2) Describe the function N() and its importance.
(3) Explain how Sage handles trigonometric functions. Include examples.
(4) Explain how matrices are represented in Sage using list of lists.
(5) Explain the functions expand(), factor(), and gcd() in polynomial computa-
tions.

5.14.3 Problems
(1) Compute the value of
 
550 1 − (1 + 0.05)−30 /0.05

Government Victoria College 133


Chapter 5. Welcome to Sage! 5.15. Plotting Graphs in SageMath

using Sage.
(2) Solve the following using Sage:

log (1.4) / log (1 + 0.045/12)

(3) Define the matrix


1 2 3
 

A = 2 4 6
 

1 1 1
and find its RREF.
(4) Perform the following operations in Sage:

⋄ Expand (x + 1)3
⋄ Factor x2 − 1
⋄ Find gcd (x2 − 1, x2 + 2x + 1)

5.15 Plotting Graphs in SageMath


5.15.1 Introduction
SageMath provides powerful tools to visualize functions graphically. Graphs help in
understanding important concepts such as behavior of functions, intersections, limits,
and continuity.

5.15.2 Basic Syntax


The general syntax for plotting a function is:

plot(f(x), x, a, b)

where:

⋄ f (x) is the function,


⋄ x is the variable,
⋄ [a, b] is the interval of plotting.

5.15.3 Basic Examples


Example 1: Plot the graph of f (x) = 2x2 − 4x + 2 on [−3, 5].

plot(2*x^2 - 4*x + 2, x, -3, 5)

Example 2: Plot the graph of f (x) = sin (2x) on [−3, 3].

plot(sin(2*x), x, -3, 3)

134 Government Victoria College


5.15. Plotting Graphs in SageMath Chapter 5. Welcome to Sage!

5.15.4 Plotting Multiple Functions


Multiple functions can be plotted on the same axes:
plot((2*x^2 - 4*x + 2, sin(2*x)), x, -3, 5)

5.15.5 Controlling the Range


To improve visibility, we can restrict the vertical range:
plot(f(x), x, a, b, ymin=-10, ymax=6)

5.15.6 Common Types of Functions


Polynomial:
plot(x^3, x, -4, 4)
Trigonometric:
plot(2*sin(x) + cos(x), x, -2*pi, 2*pi)
Exponential and Logarithmic:
plot(x*e^x + log(x), x, -3, 3)
Rational Function:
plot(2*x^2/(x^2+2), x, -4, 4)

5.15.7 Plot Options


Adding a Title:
plot(x^3, x, -4, 4, title="Graph of x^3")
Changing Size:
plot(x^2, x, -4, 4, figsize=3)
Changing Color:
plot(x^2, x, -4, 4, color=’purple’)
Line Thickness:
plot(x^2, x, -4, 4, thickness=3)
Line Style and Legend:
plot(x^2, x, -4, 4, linestyle=’--’, legend_label=’f(x)’)
Frame Around Graph:
plot(x^2, x, -4, 4, frame=True)
Axis Labels:
plot(x^2, x, -4, 4, axes_labels=[’x’, ’y’])

5.15.8 Implicit Plots


To plot curves like circles or ellipses:
implicit_plot(f(x,y), (x,a,b), (y,c,d))

Government Victoria College 135


Chapter 5. Welcome to Sage! 5.15. Plotting Graphs in SageMath

Worked Examples
Example 1: Plot f (x) = x3 with title and color.
plot(x^3, x, -4, 4, title="Cubic Function", color=’blue’)
Example 2: Plot f (x) = x2 with thickness and dashed line.
plot(x^2, x, -4, 4, linestyle=’--’, thickness=4)
Example 3: Plot two functions together:

f (x) = x2 , g (x) = sin (x)

plot((x^2, sin(x)), x, -3, 3)


Example 4: Plot a rational function with restricted range:
2x2 + x + 2
f (x) =
x+1
plot((2*x^2 + x + 2)/(x + 1), x, -5, 5, ymin=-10, ymax=10)
Example 5: Plot an ellipse using implicit plot:

x2 + y 2 = 4

implicit_plot(x^2 + y^2 == 4, (x,-3,3), (y,-3,3))

5.15.9 Exercises
[Link] Very Short Answer
(1) What is the basic command to plot a function in SageMath?
(2) What do the arguments a and b represent in plot(f(x), x, a, b)?
(3) Which function is used to plot implicit curves?
(4) Write the command to plot x2 on [−2, 2].
(5) How do you add a title to a graph?
(6) Which option is used to change the color of a graph?
(7) What does the option thickness control?
(8) What is the use of axes_labels?
(9) What does frame=True do?

[Link] Short Answer


(1) Explain the syntax of the plot() function with an example.
(2) How can you plot multiple functions on the same graph? Illustrate with code.
(3) What is the use of ymin and ymax? Give an example.
(4) Explain the difference between explicit and implicit plots.
(5) Write Sage code to plot sin (x) on [−π, π] and describe the output.

136 Government Victoria College


5.16. Differentiation in SageMath Chapter 5. Welcome to Sage!

[Link] Problems and Programming


(1) Plot f (x) = x2 − 3x + 2 on [−2, 4].
(2) Plot f (x) = sin (x) on [−π, π].
(3) Plot both f (x) = x2 and g (x) = x3 on the same axes.
(4) Plot f (x) = x1 on [−5, 5] with suitable range restrictions.
(5) Plot f (x) = ex on [−2, 2].
(6) Plot f (x) = ln (x) on [0, 5].
(7) Plot f (x) = 2 sin (x) + cos (x) on [−2π, 2π].
(8) Plot f (x) = x3 with title, color, and thickness.
(9) Plot a circle x2 + y 2 = 9 using implicit plot.
x2
(10) Plot f (x) = x2 +1
on [−5, 5].
(11) Plot the function
f (x) = 2x2 − 4x + 2
on the interval [−3, 5].
(12) Plot both functions

f (x) = x2 and g (x) = sin (x)

on the same graph.


(13) Plot the rational function

2x2 + x + 2
f (x) =
x+1
with suitable range restrictions.
(14) Perform the following:

⋄ Plot f (x) = x3 with title and color


⋄ Plot a circle x2 + y 2 = 9 using implicit plotting

5.16 Differentiation in SageMath


5.16.1 Introduction
Differentiation is a fundamental concept in calculus used to determine the rate of
change, slope of a curve, and extrema of functions. SageMath provides simple com-
mands to compute derivatives symbolically.

5.16.2 Basic Syntax


The derivative of a function is computed using:
diff(f(x), x)

Government Victoria College 137


Chapter 5. Welcome to Sage! 5.16. Differentiation in SageMath

where:

⋄ f (x) is the function,


⋄ x is the variable of differentiation.

5.16.3 Basic Examples


Example 1: Differentiate f (x) = x2 .

diff(x^2, x)

2x
Example 2: Differentiate f (x) = x3 + 2x2 + x.

diff(x^3 + 2*x^2 + x, x)

3x2 + 4x + 1

5.16.4 Higher Order Derivatives


To compute higher order derivatives:

diff(f(x), x, n)

Example:

diff(x^3, x, 2)

6x

5.16.5 Derivatives of Standard Functions


Polynomial:

diff(x^4, x)

Trigonometric:

diff(sin(x), x)

cos (x)
Exponential:

diff(e^x, x)

ex
Logarithmic:

diff(log(x), x)
1
x
138 Government Victoria College
5.16. Differentiation in SageMath Chapter 5. Welcome to Sage!

5.16.6 Product Rule


Example:
f (x) = x2 sin (x)
diff(x^2*sin(x), x)

5.16.7 Quotient Rule


Example:
x2
f (x) =
x+1
diff(x^2/(x+1), x)

5.16.8 Chain Rule


Example:  
f (x) = sin x2
diff(sin(x^2), x)
 
2x cos x2

5.16.9 Evaluating Derivatives at a Point


diff(f(x), x).subs(x=a)

Example:
diff(x^2, x).subs(x=2)
4

5.16.10 Defining Functions


f(x) = x^3 + 2*x
diff(f(x), x)

5.16.11 Important Notes


⋄ Use * for multiplication
⋄ Use ˆ for powers
⋄ Use log(x) for natural logarithm
⋄ Sage gives exact symbolic answers

Worked Examples
Example 1: Find d
dx
(x4 + 3x2 + 1).
diff(x^4 + 3*x^2 + 1, x)

Government Victoria College 139


Chapter 5. Welcome to Sage! 5.16. Differentiation in SageMath

4x3 + 6x
Example 2: Find the second derivative of x3 .

diff(x^3, x, 2)

6x
Example 3: Find the derivative of sin (x2 + 1).

diff(sin(x^2 + 1), x)
 
2x cos x2 + 1
Example 4: Evaluate d
dx
(x3 ) at x = 2.

diff(x^3, x).subs(x=2)

12

5.16.12 Exercises
(1) Find dxd
(x5 ).
(2) Differentiate 3x2 + 2x + 1.
(3) Find dxd
(sin x).
(4) Differentiate x2 cos x.
 
x2
(5) Find d
dx x+1
.
(6) Find the second derivative of x4 .
(7) Differentiate sin (x2 + x).
(8) Find d
dx
(ex log x).
(9) Evaluate dx
d
(x3 + 2x) at x = 1.
(10) Write Sage code to compute the derivative of x3 + 2x.

[Link] Very Short Answer


(1) What is the command used to compute the derivative in SageMath?
(2) What does diff(f(x), x) represent?
(3) Write the syntax for the second derivative.
(4) What is the derivative of x2 ?
(5) What is the derivative of sin (x)?
(6) What is the derivative of ex ?
(7) What is the derivative of log (x)?
(8) How do you evaluate a derivative at a point in Sage?
(9) What does diff(f(x), x, 3) represent?
(10) What is meant by higher-order derivative?

140 Government Victoria College


5.16. Differentiation in SageMath Chapter 5. Welcome to Sage!

[Link] Short Answer


(1) Explain the syntax of the diff() function.
(2) How do you compute higher-order derivatives in SageMath?
(3) What is the significance of the second derivative?
(4) Write Sage code to compute the derivative of x3 + 2x.
(5) How do you substitute a value after differentiation?
(6) Explain the role of symbolic computation in differentiation.

[Link] Conceptual Questions


(1) Explain the concept of derivative as slope of a tangent.
(2) What is the meaning of higher-order derivatives?
(3) Explain the importance of derivatives in real-life applications.
(4) Describe how SageMath simplifies differentiation.
(5) Explain the difference between first and second derivatives.

[Link] Computational Problems


(1) Find d
dx
(x4 + 3x2 + 1).
(2) Find (3x3 + 5x).
d
dx
(3) Differentiate sin (x) + cos (x).
(4) Find d
dx
(sin (2x)).
(5) Find (ex + log (x)).
d
dx
(6) Differentiate x2 sin (x).
 
x2
(7) Find d
dx x+1
.
(8) Differentiate sin (x2 + 1).
(9) Find second derivative of x3 .
(10) Find third derivative of x4 .
d2
(11) Compute dx2
(sin x).
d3
(12) Find (e ).
dx3
x

(13) Find second derivative of x2 cos (x).

[Link] Programming
(1) Write Sage code to compute:

diff(x^3 + 2*x, x)

(2) Write code to compute second derivative:

Government Victoria College 141


Chapter 5. Welcome to Sage! 5.16. Differentiation in SageMath

diff(x^4, x, 2)

(3) Write code to evaluate derivative at a point:

diff(x^2, x).subs(x=3)

(4) Write a program to define a function, compute its derivative, and evaluate it at
a point.

[Link] Application-Based Questions


(1) Find slope of tangent to y = x2 at x = 3.
(2) Use second derivative to determine concavity of y = x3 .
(3) Find rate of change of y = ex at x = 0.

[Link] Higher-Level Questions


(1) Explain differentiation rules (product, quotient, chain) with examples.
(2) Demonstrate computation of higher-order derivatives using Sage.
(3) Explain how derivatives help in analyzing graphs of functions.

[Link] Error Identification


(1) Identify error:

diff x^2, x

(2) Identify error:

diff(sin x, x)

(3) Identify error:

diff(x^2)

[Link] Multiple Choice Questions


(1) The function used for differentiation is:
(a) derive() (b) diff() (c) derivative() (d) calc()
(2) The second derivative is computed using:
(a) diff(f,x,2) (b) diff(f,2) (c) derivative(f,2) (d) calc(f,2)
(3) Derivative of cos (x) is:
(a) sin (x) (b) − sin (x) (c) cos (x) (d) − cos (x)

142 Government Victoria College


5.17. Antiderivatives (Indefinite
Integrals) Chapter 5. Welcome to Sage!

[Link] True / False


(1) Sage automatically applies chain rule.
(2) Higher-order derivatives can be computed directly.
(3) diff() works only for polynomials.
(4) The derivative of a constant is zero.

[Link] Long Questions


(1) Find derivatives of:

⋄ x5
⋄ sin (x2 )
⋄ ex log (x)

(2) Compute:

⋄ second derivative of x4
⋄ third derivative of sin (x)

(3) Evaluate derivatives at given points.

5.17 Antiderivatives (Indefinite Integrals)


An antiderivative of a function f (x) is a function F (x) such that

F ′ (x) = f (x) .

The collection of all antiderivatives is called the indefinite integral:


Z
f (x) dx = F (x) + C,

where C is the constant of integration.

5.17.1 Basic Syntax in SageMath


To compute an indefinite integral:

integrate(f(x), x)

where:

⋄ f (x) is the function,


⋄ x is the variable of integration.

Government Victoria College 143


5.17. Antiderivatives (Indefinite
Chapter 5. Welcome to Sage! Integrals)

5.17.2 Basic Examples


Example 1: Z
x2 dx
integrate(x^2, x)
x3
3
Example 2: Z  
3x2 + 2x dx
integrate(3*x^2 + 2*x, x)
x3 + x 2

5.17.3 Standard Integrals


Polynomial:
Z
xn+1
x dx =
n
, n ̸= −1
n+1
Trigonometric:
Z Z
sin (x) dx = − cos (x) , cos (x) dx = sin (x)

Exponential: Z
ex dx = ex
Logarithmic: Z
1
dx = log (x)
x

5.17.4 Constant of Integration


SageMath does not always display the constant C, but mathematically:
Z
f (x) dx = F (x) + C.

5.17.5 Linearity of Integration


Z Z Z
(af (x) + bg (x)) dx = a f (x) dx + b g (x) dx
Example:
integrate(2*x + 3, x)

5.17.6 Substitution (Basic Idea)


Example: Z  
2x cos x2 dx
integrate(2*x*cos(x^2), x)
 
sin x2

144 Government Victoria College


5.17. Antiderivatives (Indefinite
Integrals) Chapter 5. Welcome to Sage!

5.17.7 Verification of Results


We can verify results by differentiation:
diff(integrate(f(x), x), x)

Worked Examples
Example 1: Find (x3 + 2x) dx.
R

integrate(x^3 + 2*x, x)
x4
+ x2
4
Example 2: Find sin (x) dx.
R

integrate(sin(x), x)
− cos (x)
Example 3: Find
R 1
x
dx.
integrate(1/x, x)
log (x)
Example 4: Verify x2 dx.
R

diff(integrate(x^2, x), x)
x2

Exercises
(1) Find x5 dx.
R

(2) Find (2x + 3) dx.


R

(3) Find sin (x) dx.


R

(4) Find (x2 + x + 1) dx.


R

(5) Evaluate ex dx.


R

(6) Find x1 dx.


R

(7) Evaluate x cos (x2 ) dx.


R

(8) Find (3x2 + sin x) dx.


R

(9) Write Sage code to compute:

integrate(x^3, x)

(10) Verify sin x dx.


R

Government Victoria College 145


5.18. Riemann Sums and Definite
Chapter 5. Welcome to Sage! Integrals

5.18 Riemann Sums and Definite Integrals


5.18.1 Introduction
A definite integral represents the area under a curve between two points a and b:
Z b
f (x) dx
a

It can be approximated using Riemann sums, which divide the interval into subintervals
and sum the areas of rectangles.

5.18.2 Partition of an Interval


Divide [a, b] into n equal parts:
b−a
∆x =
n
Subinterval points:
x0 = a, x1 = a + ∆x, . . . , xn = b

5.18.3 Riemann Sum (General Form)


n
f (x∗i ) ∆x
X

i=1

where x∗i is a point in the i-th subinterval.

5.18.4 Definite Integral as a Limit


Z b n
f (x) dx = lim f (x∗i ) ∆x
X
a n−
→∞ i=1

5.18.5 SageMath Syntax


integrate(f(x), x, a, b)

Example: Z 1
x2 dx
0

integrate(x^2, x, 0, 1)
1
3

5.18.6 Interpretation
⋄ Area above the x-axis is positive
⋄ Area below the x-axis is negative
⋄ Integral gives net signed area

146 Government Victoria College


5.19. Riemann Sum Using Left
Endpoints Chapter 5. Welcome to Sage!

5.19 Riemann Sum Using Left Endpoints


5.19.1 Left Endpoint Method
In this method, the height of each rectangle is taken at the left endpoint of each
subinterval.

5.19.2 Formula
n−1
f (xi ) ∆x, where xi = a + i∆x
X

i=0

5.19.3 SageMath Implementation


sum([f(a + i*dx)*dx for i in range(n)])

5.19.4 Steps
(1) Define the function f (x)
(2) Set interval [a, b]
(3) Choose number of subintervals n
(4) Compute ∆x = b−a
n

5.19.5 Example
Approximate: Z 1
x2 dx using n = 4
0

f(x) = x^2
a = 0
b = 1
n = 4
dx = (b-a)/n

sum([f(a + i*dx)*dx for i in range(n)])

5.19.6 Table Representation


table([(i, a + i*dx, f(a + i*dx)) for i in range(n)])

5.19.7 Accuracy
⋄ Increasing n improves approximation
⋄ As n −
→ ∞, sum approaches exact integral

5.19.8 Comparison with Exact Value


integrate(f(x), x, a, b)

Government Victoria College 147


5.19. Riemann Sum Using Left
Chapter 5. Welcome to Sage! Endpoints

Worked Examples
Example 1: Approximate x dx using n = 4.
R2
0

f(x) = x
a = 0
b = 2
n = 4
dx = (b-a)/n

sum([f(a + i*dx)*dx for i in range(n)])

Example 2: Find exact value:

integrate(x, x, 0, 2)

Example 3: Display table:

table([(i, a + i*dx, f(a + i*dx)) for i in range(n)])

Exercises
(1) Compute x dx using Sage.
R1
0
(2) Approximate using left endpoints with n = 5.
R1 2
0 x dx
(3) Approximate 0 x dx using n = 10.
R2 2

(4) Compare exact and approximate values.


(5) Approximate 0π sin (x) dx.
R

(6) Study the effect of increasing n.


(7) Write Sage code for left Riemann sum.
(8) Display a table of values.
(9) Compare results with exact integral.

148 Government Victoria College

You might also like