0% found this document useful (0 votes)
3 views100 pages

Python Sample

This book, authored by Rachna Verma and Arvind Kumar Verma, serves as a comprehensive introduction to Python programming, covering both basic and advanced concepts. It includes numerous examples and practice problems, making it suitable as a textbook for students. The content is designed to help readers solve real-life industrial and academic problems using Python.
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)
3 views100 pages

Python Sample

This book, authored by Rachna Verma and Arvind Kumar Verma, serves as a comprehensive introduction to Python programming, covering both basic and advanced concepts. It includes numerous examples and practice problems, making it suitable as a textbook for students. The content is designed to help readers solve real-life industrial and academic problems using Python.
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

First Edition

Introduction to Python

Rachna Verma
Arvind Kumar Verma
i
Introduction to Python

First Edition (eBook)

Rachna Verma
Professor of Master of Computer Application,
Faculty of Engineering and Architecure,
JNV University, Jodhpur, Rajasthan, India

Arvind Kumar Verma


Professor of Production and Industrial Engineering,
Faculty of Engineering and Architecture,
MBM University, Jodhpur, Rajasthan, India

ii
Introduction to Python
Copyright © 2024 Dr. Rachna Verma and Dr. Arvind Kumar Verma
ISBN:
First published in India by Dr. Rachna Verma and Dr. Arvind Kumar Verma
All rights reserved. No part of this publication may be reproduced or distributed
in any form or by any means, or stored in a data base or retrieval system, without
the prior written permission of the authors.
Cover (illustration) by Dr. Rachna Verma
Set by Dr. Rachna Verma
Published by [Link]

This book provides a comprehensive, hands-on introduction to Python, a


powerful and one of the most widely used computer programming language.
Starting with basic concepts, the book lucidly builds advanced Python
programming concepts one needs for solving real-life industrial and academic
problems. The book contains a large number of illustrative examples and
practice problems. The book is well suited as a textbook for learning Python for
students. It is sold under the express understanding that the information

the authors will not be held responsible for the consequences of any actions
based on the content of the book for any purpose.

iii
Introduction to Python
Table of contents

Preface xiii
1. Introduction to Computing 1
1.1 Components of a Computer 1
1.1.1 Input Devices 2
1.1.2 Output Devices 2
1.1.3 Central Processing Unit 2
1.1.4 Memory 4
1.2 Computer Software 4
1.2.1 Types of System Software 5
1.3 Programming Languages 7
1.3.1 Types of Computer Programming Languages 9
1.4 Algorithms and Flowcharts 12
1.4.1 Guidelines to Write Algorithms 13
1.4.2 Examples of Some Algorithms 14
1.4.3 Pseudocode 17
1.4.4 Flowchart 18
1.4.5 Examples of Flowcharts 19
1.4.6 Python Programs 25
2 Overview of Python 33
2.1 History of Python 33
2.2 Why Python? 34
2.3 Installing Python 35
2.4 Starting Python In Windows 39
2.4.1 Python Command Prompt 39

iv
2.4.2 Python IDLE 41
2.5 Structuring Python Programs 44
2.5.1 Python Statements 44
2.5.2 Line Continuation 45
2.5.3 Comments in Python 46
2.5.4 Proper Indentation 48
2.6 Structure of a Python Program 49
2.7 Coding Style 51
2.8 Identifier Naming Convention 52
2.9 Python Implementations 53
2.10 Python IDEs 54
2.11 Python Distributions 55
3 Basics of Python Programming 61
3.1 Character Set 61
3.2 Python Token 63
3.3 Keywords 63
3.4 Identifiers 66
3.4.1 Rules for Naming Identifiers 67
3.5 Literals and Datatypes 68
3.5.1 String Literals 68
3.5.2 Numeric Literals 75
[Link] Integer Literals 75
[Link] Floating-Point Literals 77
[Link] Complex Number Literals 78
3.5.3 Boolean Literals 79
3.5.4 Collection Literals 80
[Link] List Literals 80
[Link] Tuple Literals 81
[Link] Dictionary Literals 82
[Link] Set Literals 84
3.5.5 Special Literal None 85
3.6 Variables 86
v
3.7 Operators 87
3.8 Delimiters 88
3.9 Input and Output Functions 90
3.9.1 The Input Function 90
3.9.2 Reading Single Numeric Data 92
3.9.3 Reading Multiple Numeric Data Separated with a Delimiter 95
3.9.4 The Eval Function 97
3.9.5 The Print Function 100
3.10 Formatting Numbers and Strings 102
3.10.1 The Traditional % Formatting Operator 102
3.10.2 The Format Function 106
3.10.3 Formatting with the Format Method of the Str Object 109
3.10.4 F-String in Python 112
4 Operators and Expressions 123
4.1 Operators 123
4.1.1 Arithmetic Operators 123
4.1.2 Relational (Comparison) Operators 129
4.1.3 Logical Operators 130
4.1.4 Bitwise Operators 133
4.1.5 Assignment Operators 135
4.1.6 Membership Operators 139
4.1.7 Identity Operators 141
4.2 Expressions 143
4.2.1 Arithmetic Expressions 143
4.2.2 Logical Expressions 145
4.2.3 String Expressions 146
4.3 Operator Precedence and Associativity 147
4.4 Statements vs Expressions 150
4.5 Python Built-in functions 150
4.6 Importing Mathematic Functions 167
5 Decision Making and Branching 189
5.1 if Statement 189
vi
5.2 if-else Statement 193
5.3 Nested if Statement 195
5.4 Ladder if (if-elif-else) Statement 198
5.5 Ternary Operator 203
5.6 pass Statement 206
6 Loop Control Statements 219
6.1 while Loop 220
6.2 for Loop 224
6.3 break Statement 226
6.4 continue Statement 229
6.5 else Statement 233
6.6 Nested Loops 236
6.7 quit () and exit () Functions 236
7 User-Defined Functions 261
7.1 Introduction 261
7.2 Defining a User-defined Function 265
7.3 Parameters and Arguments in a Function 267
7.3.1 Positional Parameters 268
7.3.2 Parameters with Default Values 268
7.3.3 Keyword Arguments 269
7.3.4 Variable Number of Parameters 271
7.4 Calling a Function 273
7.5 Local and Global Functions 276
7.6 Scope and Life of a Aariable 277
7.6.1 Local Variables 277
7.6.2 Global Variables 278
7.7 Passing Arguments to a Function 281
7.8 Return Values from Functions 285
7.8.1 Returning Multiple Values from a Function 286
7.9 Passing and Returning Function Objects to a Function 288
7.10 Recursive Functions 289

vii
7.11 Lambda Function 290
7.12 Generator Functions 291
7.13 Command Line Arguments 293
8 Lists 315
8.1 List Creation 315
8.1.1 Lists from Data 315
8.1.2 Converting Other Data Types to Lists 316
8.1.3 List Comprehension to Create a New List 318
8.1.4 Split a String into a List of Words 321
8.2 Accessing an Element of a List 321
8.2.1 List Traversal 323
8.3 List Slicing 324
8.3.1 Traversing Sliced List 326
8.4 Commonly Used Built-in Function for Lists 327
8.4.1 The max() and min () Functions for a List of Lists or Iterables 330
8.4.2 The max () and min () Functions with a List of Complex 332
numbers
8.5 Creating Copies of a List 332
8.5.1 Reference Copy 334
8.5.2 Shallow Copy 336
8.5.3 Deep Copy 338
8.6 Methods of the list Class 338
8.7 Random Reshuffle of the Elements of a List 341
8.8 Using a List as a Matrix and an Array 343
8.8.1 Creating a Matrix from Data 343
8.8.2 Creating an Array from data 345
8.8.3 Reading a Matrix from the Keyboard 349
8.8.4 Nested List Comprehension to Process Matrices 351
8.9 List Operators 353
9 Strings 377
9.1 Creating String Objects 377
9.1.1 Assigning a String Literal to a Variable 377
viii
9.1.2 Using the Construction of the string Class 378
9.2 Built-in Functions for Strings 379
9.3 Accessing Characters in a String 379
9.4 Traversing a String 380
9.5 Slicing Operation with a String 381
9.6 String Operators 383
9.7 String Class Methods 383
10 Tuples, Sets and Dictionaries 403
10.1 Tuple 403
10.2 Create Tuples 404
10.2.1 From Data 404
10.2.2 From Other Iterables 404
10.2.3 Using Comprehension 405
10.3 Built-in Functions for Tuples 407
10.4 Indexing of Tuple Elements 409
10.5 Slicing of Tuples 410
10.6 Operations on Tuples 410
10.7 Traversing Tuples 411
10.8 Sorting a Tuple 413
10.9 Zipping Tuples Together 413
10.10 Tuple Methods 414
10.11 Lists and Other Mutable Sequences as Elements of Tuples 415
10.12 Tuple vs List 416
10.13 Sets 417
10.14 Creating Sets 417
10.15 Built-in Functions for Sets 419
10.16 Membership Operators: in and not in 420
10.17 Set Methods 420
10.18 Traversing Sets 424
10.19 Frozenset 425
10.20 Dictionaries 426
10.21 Creating Dictionaries 426
ix
10.22 Accessing a Dictionary Element 430
10.23 Nested Dictionary 430
10.24 Removing an Element from a Dictionary 431
10.25 Traversing a Dictionary 431
10.26 Built-in Functions for Dictionaries 432
10.27 Methods of the dict Class 433
11 File Handling 453
11.1 Types of Files 453
11.2 Steps in File Handling 454
11.3 Opening a File 455
11.4 Reading from a Text File 462
11.5 Writing into a Text File 465
11.6 Writing Numbers and Booleans in a File 467
11.7 Reading Numbers from a File 468
11.8 Seek and Tell Methods 469
11.9 Iterating Over Lines in a File 471
11.10 Accessing Binary Files 471
11.11 Serialization in Python 476
11.11.1 The pickle Module 477
11.11.2 The json Module 478
11.12 CSV Files 485
11.13 File and Directory Management 488
12 Object Oriented Programming in Python 513
12.1 Basic concepts of Object-Oriented Programming 514
12.1.1 Objects and Classes 514
12.1.2 Data Encapsulation 515
12.1.3 Inheritance 515
12.1.4 Polymorphism 518
12.1.5 Dynamic Binding 519
12.1.6 Message Passing 519
12.2 Define a Class in Python 520
12.3 Constructors and Destructor 524
x
12.4 Encapsulation in Python 528
12.5 Instance Methods 531
12.6 Name Mangling 533
12.7 Display Class Attributes and Instance Methods 534
12.8 Inheritance in Python 536
12.9 Types of Inheritance in Python 540
12.10 The object Class 543
12.11 Method Resolution Order in Python 544
12.12 Type and Class Membership Tests 548
12.13 Polymorphism in Python 550
12.14 Method Overloading 550
12.15 Operator Overloading 552
12.16 Overloading Built-in Python Functions 557
12.17 Decorator Classes 558
13 Exception Handling in Python 576
13.1 Python Built-in Exceptions 578
13.2 Handling a General Exception 581
13.3 Catching Specific Exceptions 582
13.4 Raising Exceptions 589
13.5 User-defined Exception 590
13.6 Assertions 592
14 Introduction to NumPy 603
14.1 Introduction 603
14.2 NumPy Arrays 603
14.3 Data structure of NumPy arrays 605
14.4 Creating Arrays in NumPy 607
14.5 Attributes of the ndarray Class 618
14.6 Indexing and Slicing NumPy Arrays 620
14.7 Operations on NumPy Arrays 626
14.7.1 Element-wise Operations 626
14.7.2 Matrix and Linear Algebra Functions 629
14.7.3 Reduction Operations on Arrays 635
xi
14.7.4 Broadcasting NumPy Arrays 637
14.7.5 Array Shape Manipulation 639
14.7.6 Sorting Data 643
14.8 Structured NumPy Arrays 644
15 Introduction to Matplotlib 663
15.1 Steps to Create a Plot in Matplotlib 663
15.2 The plot Method 666
15.3 Creating Sub-plots 670
15.4 Customizing a Plot 672
15.4.1 Adding Axis Labels and Plot Titles 672
15.4.2 Adding a Grid to a Plot 674
15.4.3 Adding Ticks and Tick-labels 676
15.4.4 Adding Legends 678
15.4.5 Twin Axis 680
15.5 Bar Charts 682
15.6 Histogram Plots 687
15.7 Pie Chart 689
15.8 Scatter Plots 691
15.9 Contour Plots 692
15.10 Box Plots 694
15.11 Violin Plots 696
15.12 Quiver Plots 698
15.13 3D Plots 700
15.14 3D Contour Plots 703
15.15 Wireframe and Surface Plots 705
15.16 Animation using Matplotlib 707
15.16.1 Steps to Create an Animation Plot using FuncAnimation 708
15.16.2 Steps to Create Animation Plot using ArtistAnimation 710
16 GUI Applications using tkinter 727
16.1 Introduction to Graphics User Interface 727
16.2 Components of Event Driven Programming 729

xii
16.2.1 Widgets 729
16.2.2 Events 731
16.2.3 Event Listener Functions 735
16.3 Creating a GUI Application using the tkinter Module 735
16.4 Creating and Customizing the Main Application Window 739
16.5 Creating Widgets 741
16.5.1 Standard Attributes of Widgets 742
16.5.2 Geometry Layout Manager 750
16.6 Button Widget 765
16.7 Canvas Widget 768
16.8 Checkbutton Widget 779
16.9 Entry Widget 783
16.10 Frame Widget 785
16.11 Label Widget 787
16.12 Listbox Widget 788
16.13 Menu Widget 795
16.14 Menubutton Widget 799
16.15 Message Widget 801
16.16 Radiobutton Widget 802
16.17 Scale Widget 804
16.18 Scrollbar Widget 806
16.19 Text Widget 808
16.20 Toplevel Widget 811
16.21 Spinbox Widget 812
16.22 Messagebox Widget 814
Index 824

xiii
Preface
Python is a very powerful and one of the most widely used computer programming
language for general purpose, scientific and technical computations. Its popularity is
due to a huge collection of library functions and very easy to learn. Further, a large
number of help material and forums are available for Python. Since it is freely available,
many commercial developers are also using it to reduce their project cost and has
reported many successful applications.

This book is written following several years of teaching the Python programming
course to our students. The basic objective to write this book is to teach Python in a
friendly, non-intimidating fashion to students who have no previous programming
knowledge and experience. Therefore, the book is written in simple language with many
sample problems in mathematics, science, and engineering. Starting from the basic
concepts, the book gradually builds advanced concepts, making it suitable for freshmen
and professionals. This makes this book unique among the many books available in the
market which assume previous knowledge of a programming language. The book deals
with the latest version of the language.

For promoting outcome-based learning, each chapter of the book starts with chapter
learning objectives and lucidly introduces the basic concepts, with sample examples, to
achieve those objectives. Each chapter concludes with a summary. Finally, the chapter
ends with multiple choice questions, review questions and programming assignments
so as students can apply the concepts learned in the chapter.

The book consists of sixteen chapters. Chapter 1 introduces the basic concepts of
Computing, algorithms, flowcharts and programming. Chapter 2 gives an overview of
Python programming language. Chapter 3 gives the basics of Python Programming.
Chapter 4 discusses the operators available in Python and concepts of expressions.
Chapter 5 introduces the basic concepts of decision making and branching constructs of
Python. Chapter 6 explains loop control statements. Chapter 7 discusses User-Defined
Functions. Chapter 8 introduces the basic concepts of Lists. Chapter 9 describes
Strings. Chapter 10 covers Tuples, Sets and Dictionaries. Chapter 11 describes File
Handling in Python. Chapter 12 presents the basic concepts of Object Oriented
Programming in Python. Chapter 13 briefly explains Exception Handling in Python.
Chapter 14 introduces NumPy forefficeint numerical computations. Chapter 15 gives
overview of Matplotlib to create charts. And Chapter 16 discusses GUI Applications
using tkinter.
xiv
We hope that the book will be useful in lucidly building expertise in Python
programming to the readers. We sincerely welcome any suggestion to further improve
the book. Authors can be reached at [Link]@[Link], [Link]@[Link]
and rachnaverma@[Link] .

Rachna Verma

Arvind Kumar Verma

xv
About the Authors

Dr. Arvind Kumar Verma is working as a Professor, Department of Production


and Industrial Engineering, MBM University, Jodhpur, Rajasthan, India. He
received his BE (Industrial Engineering) and ME (Production and Industrial
Systems Engineering) from IIT Roorkee, India and obtained his PhD in
CAD/CAM from MBM Engineering College, Jai Narain Vyas University,
Jodhpur, Rajasthan, India. He has 30 years of teaching experience. He teaches
numerical methods, CAD/CAM, robotics, and computer programming. He has
research interest in robotic vision, machining feature recognition and numerical
computation.

Dr. Rachna Verma is working as a Professor of Master of Computer Application,


Faculty of Engineering, Jai Narain Vyas University, Jodhpur, Rajasthan, India.
She received her BSc (Math Honours) form Delhi University, India and MCA
and PhD from JNV University, Jodhpur, India. She has 21 years of teaching
experience. She teaches numerical methods, computer programming and
computer graphics, visual computing, Machine learning and Data Science and
has research interest in deep learning, computer vision and image processing.

xvi
xvii
Chapter 1

Introduction to Computing
Learning outcomes
1. Describe computer, its components, and its functioning
2. Describe different types of software
3. Describe types of programming languages
4. Develop programming logic using flowcharts and algorithms

According to the Cambridge dictionary, a computer is an electronic machine used


to store, organize, and find words, numbers, and pictures, do calculations and control
other devices. It has a significant impact on every aspect of our life and profession.
Engineering, science, medicine, commerce, and even social sciences are widely using
computers. Hence, computer literacy and knowledge are now essential skills for every
profession. Computing is now one of the most sought-after careers that involve using
computers for data processing to efficiently and economically solving real-life problems.
To effectively use a computer, a basic understanding of various computer components
and computer programming are essential for students and professionals.

1.1 Components of a Computer


A computer system has two main components: hardware and software. The physical
parts, such as keyboard, mouse, display unit, CPU, associated with a computer system
is called hardware. On the otherhand, software is a set of instructions that tells the
hardware what to do. Figure 1.1 shows a block diagram of major hardware components
of a computer: input devices, central processing unit, memory, and output devices.
Arrows indicate the direction of the flow of data/information among different
components.

1
Input devices Central processing unit Output devices

Memory

Figure 1.1: Components of a computer

1.1.1 Input Devices

An input device reads data. The data can be in the form of numbers, texts,
images/videos, sound waves, etc. The read data can either be processed by the CPU or
stored in memory. The typical input devices are keyboards, mice, scanners, cameras,
joysticks, microphones.

1.1.2 Output Devices

An output device in a computer is a device that converts information produced by


the CPU into human-readable form. The outputs produced by these devices can be in the
form of texts/numbers, images/videos, audio. The typical output devices are visual
display units (monitors), printers, plotters, speakers.

1.1.3 Central Processing Unit

A central processing unit (CPU) is an electronic circuitry, usually a VLSI circuit, in a


computer that executes computer programs. It is responsible for all the data processing
and performs basic arithmetic, logic, controlling, and input/output (I/O) operations
specified by the instructions in a program. Primarily, a CPU consists of arithmetic and
logic unit (ALU), control unit (CU), internal memory (also called registers), instruction
decoder, and buses (set of wires to transfer data from one place to another). Figure 1.2
shows a detailed block diagram of a computer along with components of a CPU. Functions
of various compoments of a CPU are as given below:

Arithmatic and logic unit: The ALU unit consists of electronic circuits to perform addition,
subtraction, comparison, and other operations.

2
Instruction decoder: The instruction decoder unit decodes the instruction to be executed
by the processor.

Control Unit: The control unit generates required control signals to different components
for their operations. Due to this, CU is called the brain of a computer.

Registers and Cache memory: To efficiently perform various operations, the CPU has a
few high-speed internal memories, commonly known as registers. In addition to the above,
to further reduce the memory access time and enhance the computational speed of
computers, modern-day CPUs have additional high-speed memory called cache memory.

Busses: Busses, a bunch of wires, are used to exchange data and control signals among
various components. In figure 1.2, they are shown with lines.

CPU Data flow


Instruction decoder
Control flow

Control unit

Input devices Arithmetic and logic unit Output devices

Registers

Memory

Figure 1.2: Detailed block diagram of a computer

3
1.1.4 Memory

Computer memory is a physical device where data/information and programs can be


stored and retrieved, such as RAM, ROM, hard disk, flash memory. Some computer
memories are high-speed but volatile (e.g., RAM), while others are slow but permanent
(e.g., hard disk). Figure 1.3 shows a classification of different types of memory: primary
and secondary. The CPU of a computer can directly interact only with the primary
memory. The primary memory is also known as the main memory. Examples of primary
memory are RAM, ROM, and Cache. Unlike the primary memory, the CPU cannot directly
interact with the data stored in a secondary memory. The data stored in a secondary
memory are first loaded into the primary memory for further processing. Examples of
secondary memory are hard disk, solid-state disk/drive, flash drive, magnetic tape. The
secondary memory is slower than the primary memory. Computer memories are also
classified as volatile and non-volatile memory. The volatile memory losses its data once
the computer power is turned off, for example, RAM. The non-volatile memory, such as
ROM, hard disk, and pen drive, is permanent and retains its data even after turning off a
computer.

Computer memory

Primary memory Secondary memory

Figure 1.3: Different types of computer memory

1.2 Computer Software


Computer software is a set of instructions to be executed on a computer to solve
problems. The software is classified as system software and application software,
depending on the type of task it performs. The system software is a computer program
designed to operate and manage computer hardware, and create and run application
4
programs, such as Linux, Windows, C++, Python. On the other hand, the application
software performs a specific type of task for the user. There is a vast list of application
software. Some common examples are image editing (Adobe Photoshop, MS Paint),
word processing (MS Word, Notepad), electronic spreadsheet (MS Excel), database
management (MySQL, Oracle, MS Access), accounting (Tally), creating engineering
drawings (AutoCAD, Solid work). Figure 1.4 shows the relationship between computer
hardware and software. Table 1.1 compares system software and application software.

1.2.1 Types of System Software

System Software can be of the following types, based on the kind of work they perform:

(a) Operating systems: An operating system, commonly called OS, is computer


software that works as an interface between a computer user and computer
hardware. The operating system typically performs file management, memory
management, process management, handling input and output devices. Commonly
used operating systems are MS Windows, Linux, Unix.

(b) Programming languages: A programming language is a program that provides


tools to develop/modify the software. As computers can process instructions given
as binary numbers (consisting of 1s and 0s), programming languages help to create
instructions in human-readable English-like languages (called source code) and
convert them into computer-understandable binary instructions (called executable
program). Some popular programming languages are C, C++, Java, Python, PHP,
JavaScript, C#, R, Swift, Kotlin.

(c) Utility programs: Utility programs help users in system maintenance tasks and
perform tasks of routine nature. Common utility tasks are disk defragmentation,
disk clean-up, compression, virus cleaning. Some examples are CCleaner,
Everything, Partition Wizard, WinZip.

5
User

Application Software

System Software

Hardware (CPU, Keyboard,


Mouse, Monitor, Printer, etc.)

Figure 1.4: Relationship of computer hardware and software

Table 1.1: Comparison of system and application software

S. No. System Software Application Software

1. System software manages computer Application software is used to


hardware and application software. solve a specific task of the user.

2. System software, specifically an Application software is installed


operating system, is essential for as per the
computer operations.

3. Usually, a user does not directly In general, a user directly interacts


interact with the system software as it with an application software and
works in the background. provides the necessary inputs.

4. A system software can run Application software requires an


independently. operating system to run.

6
1.3 Programming Languages
A computer is an electronic machine that processes a set of predefined binary codes,
called machine instructions. Each code drives the computer circuit to perform a particular
task. A program is a set of machine instructions and it can be written in different ways as
given below:

Machine level programming: For example, on the execution of the binary code 1010000
(equal to 80 in hexadecimal) on an 8085 microprocessor, the processor will add the number
stored in register B with the number stored in register A and store the result back in register
A. A computer program is a set of such binary codes written in a particular sequence to
solve a problem. However, it is incredibly tedious and cumbersome to write instructions
manually in binary codes (called machine-level programming) even for simple tasks.
Further, each different type of CPU has its unique machine codes, making programming
more complex.

Assembly-level programming: To overcome the above difficulties, programmers started to


use symbolic codes (called mnemonics) in place of binary codes. This programming style is
called assembly-level programming. For example, instead of writing code 1010000 (or 80),
an assembly program uses ADD B. Each machine instruction is mapped to a unique
mnemonic. A computer program, called assembler, is used to covert an assembly program
into an equivalent machine code program. The assembly programming made the life of a
programmer a bit easier, but it is still a very tedious task to write complex programs.

High-level languages: To make programming easier, many human-readable English-like


languages (called high-level languages) are now widely used. Again, with the help of
compilers/interpreters, programs written in high-level languages are converted into
machine code programs. Please note, even a modern computer still understands machine
codes only. Figure 1.5 shows levels of computer programming based on the ease of
programming.

7
Ease of programming
Python, Java, C++, C,
FORTRAN, JavaScript
High Level Languages

Assembly code

Machine code

Computer hardware

Figure 1.5: Levels of computer programming

A programming language uses a predefined vocabulary, and grammatical and


syntax rules for creating instructions for a computer or computing device to perform
specific tasks. A programming language provides facilities to create/modify a program and
convert the program into executable codes. Usually, the term programming language refers
to a high-level programming language, such as BASIC, C, C++, Java, FORTRAN, Python.
Each programming language has a unique set of vocabulary (keywords) and a special
syntax for organizing program instructions.

Every language has its strengths and weaknesses. For example, FORTRAN is
suitable for scientific data processing but has no mechanism to organize and manage large
programs. C++ and Java have powerful object-oriented features, but it is complex and
challenging to learn. Python is suitable for interactive programming but slower in
comparison to C.

According to IEEE Spectrum's interactive ranking of programming languages,


Python is the top programming language of 2020, followed by C, Java, and C++. However,
the choice of a programming language depends on the nature of the task in hand, the target
computer, and the programmer's expertise.

8
1.3.1 Types of Computer Programming Languages

A computer program, called source code, can be written any plain text editor, such
as Notepad, Notepad++. However, most modern programming languages have their
integrated development environments (IDE) to create/edit, compile and run a program. A
computer program written in any programming language is finally converted into machine
codes so that the computer can understand and process it. Based on the ways high-level
programs are converted into machine codes, a programming language can be classified as
a compiled, interpreted, or intermediate programming language.

Compiled programming language: In a compiled programming language, the complete


source code of a program is directly converted into an executable machine code in one go.
Examples of compiled languages are C, C++, Erlang, Haskell, Rust, and Go.

A source code passes through several steps before it is converted into an executable
program. Figure 1.6 shows the major steps of this conversion. The basic steps to generate
an executable program are:

In the first step, the compiler checks syntax errors in the source code, and if there is no
error, it converts the high-level source code into an assembly code.

In the second step, the assembler converts the assembly code into the native object code,
i.e. machine code of a particular machine.

Finally, the linker combines the object code, libraries, and other object codes into an
executable program. Every language has libraries of commonly used tasks, such as to
find square root, sine of an angle, etc. Other object codes are precompiled user defined
sub-programs.

Interpreted programming language: In an interpreted programming language, the


interpreter checks for the syntax errors and executes the program line-by-line. After running
a statement, it moves to the following statement of the program. If there is a syntax error in
a statement, the program's execution stops; otherwise, the execution will continue until the
program's end.

Figure 1.7 shows a block diagram of an interpreted programming language.


Interpreted languages are generally slower than compiled languages, but with just-in-time
compilation, the interpreted languages have comparable performance compared to

9
compiled languages. Examples of popular interpreted languages are PHP, Ruby, Python,
and JavaScript.

Intermediate programming language: In an intermediate programming language, the


high-level source code is first converted into a machine and platform-independent byte
code. Finally, a virtual machine (a virtual machine is a software) interprets the byte code
instructions and translates them into computer-specific machine codes. Figure 1.8 shows a
block diagram of an intermediate programming language. The major advantage of this
approach is that the same byte code can be executed on different types of CPUs and
operating systems without needing recompilation. However, this approach requires a
virtual machine for each type of computer and operating system. Due to one extra step, it
is a bit slower than purely compiled languages. A popular example of the intermediate
language is Java. Table 1.2 compares compiled and interpreted languages.

Source code

Specific Compiler

Assembly code

Assembler

Object code

Other object
Libraries Linker codes

Executable code

Figure 1.6: Block diagram of a compiled language

10
Source code

Runtime libraries Specific interpreter

Executable code

Figure 1.7: Block diagram of an interpreted programming language

Source code

Generic compiler

Byte code

Virtual Virtual Virtual


machine machine machine
Linux Windows Mac OS

Executable code Executable code Executable code

Figure 1.8: Block diagram of an intermediate language

11
Table 1.2: Comparison of compiled and interpreted languages

[Link]. Compiled language Interpreted language

1 A compiled language uses a An interpreted language uses an


compiler to convert source codes into interpreter to convert source codes
machine codes. into machine codes.

2 In a compiled language, the complete In an interpreted language, the


program is compiled and converted source code is converted into
to machine codes in one go. machine code line-by-line.

3 Compiled programs run faster than Interpreted programs run slower


interpreted programs. than compiled programs.

5 A single error in the source program Execution of the program halts at the
stops the whole compilation process. occurrence of the first error.

6 The executable code is self-sufficient The interpreter is required on the


to execute and does not require the target machine to execute the
compiler on the target machine. program.

8 Examples of compiled language are Examples of Interpreted language are


C, C++, C#, COBOL, FORTRAN. JavaScript, Perl, Python, PHP,
BASIC.

1.4 Algorithms and Flowcharts

Before writing a computer program for a problem, the programmer should


understand the logic and steps to solve the problem. However, as the complexity of a task
increases, the complexity of the logic and steps also increases. The solution of a complex
real-life problem invariably involves a large number of arithmetic and logical operations.
Further, it is essential to execute these operations in a particular sequence to achieve the
desired results. To develop proper flow and write error-free programs, programmers
frequently use algorithms and flowcharts to visualize the logic and steps of complex tasks.
Hence, algorithms and flowcharts are very powerful tools for developing good

12
programming skills. It is strongly recommended that a learner should master to use these
tools.

An algorithm is a step-by-step problem-solving steps of a task, whereas a flowchart


is a graphical representation of the same. Both algorithms and flowcharts are very helpful
and productive tools to clarify the steps to solve a complex problem. These tools do not
depend on any programming language, computer system, or operating system. Hence, they
are very versatile in nature.

Irrespective of the complexity, size, and nature of a computer programming task,


we can group instructions used to solve the task into three categories: (1) imperative
statements, (2) conditional statements, and (3) iterative statements.

1. Imperative statements: Imperative statements are result-producing action


statements, i.e., they take some data, process them, and return some results, for
example, the addition of two numbers.

2. Conditional statements: Conditional statements help in choosing the execution


flow branches based on some condition. They help in implementing statements like,
do this if this condition is true or do that if some other condition is true. For example,
for an integer value x, if x is divisible by 2, x is an even number; else, x is an odd
number.

3. Iterative Statements: Iterative statements help in repeating the execution of a set of


instructions many times. For example, to print numbers between 1 and 100, we
repeat the statement print (x) for the value of x starting with 1 and increment it by 1
till x reaches 100.

This classification of instructions helps to use standard constructions and symbols


to write algorithms and create flowcharts. Students are encouraged to use these planning
tools to develop logic to solve problems instead of directly jumping to start writing
computer programs. In the long run of their career, this habit is very valuable and
productive.

1.4.1 Guidelines to Write Algorithms

An algorithm is a finite set of steps designed to solve a task. There are no defined rules
to write algorithms, but the following are some guidelines that help in writing practical
algorithms:

13
Identify the input and output required to solve a task.

Break the tasks into precise and small steps to easily convert them into statements
of a target programming language. Each step in the algorithm should be clear and
unambiguous.

Use pseudocodes or a natural language to write an algorithm. An algorithm should


avoid using computer codes of a particular programming language.

Algorithms should use the most effective and efficient way out of the different ways
to solve a problem.

Use proper indentations to effectively implement and visualize different


programming constructs, such as looping and branching.

1.4.2 Examples of Some Algorithms

Following are some examples of algorithms.

Example 1.1: An algorithm to add two numbers entered by the user.

Step 1: Start
Step 2: Read num1 and num2.
Step 3: Calculate sum = num1+num2
Step 4: Print sum
Step 5: Stop

Example 1.2: An algorithm to find the largest number among three different
numbers.

Step 1: Start
Step 2: Input a, b and c.
Step 3: If a > b

14
If a > c
x=a
Else
x= c
Else
If b > c
x=b
Else
x=c
Step 4: Print x
Step 5: Stop

Example 1.3: An algorithm to find roots of a quadratic equation ax2 + bx + c = 0.

Step 1: Start
Step 2: Read coefficients a, b and c of the equation
Step 3: Calculate discriminant D = b2 - 4ac

r1 = (-
r2 = (-b-
Print Real roots are: r1 and r2.
Else
Calculate real part rp = -b/2a
-D)/2a
Print Complex roots are: rp+j(ip) and rp-j(ip)

15
Step 5: Stop

Example 1.4: An algorithm to calculate the factorial of a number entered by


the user.

Step 1: Start
Step 2: Read n
Step 3: Initialize factorial =1 and i=1
Step 4: Repeat the steps until i = n
factorial = factorial*i
i = i+1
Step 5: Print factorial
Step 6: Stop

Example 1.5: An algorithm to check whether a given number is a prime


number or not.

Step 1: Start
Step 2: Read n
Step 3: Initialize flag = 1 and i = 2
Step 4: Repeat the following steps until i <=(n/2)
If remainder of n/i equals 0
flag = 0
go to step 5
i= i+1
Step 5: If flag == 0

16
Print n is not prime
else
Print n is prime
Step 6: Stop

1.4.3 Pseudocode

Some programmers use pseudocode to write algorithms. It is written using plain


language describing implementation of an algorithm. In computer programming,
pseudocode is a more structured convention to write algorithms than simple algorithms. It
is intended for human reading and does not use strict programming constructs and
syntaxes. Since pseudocodes are not specific to any programming language, a programmer
with a different programming background can easily understand it. Example 1.6 uses
pseudocode to write an algorithm.

Example 1.6: A pseudocode to check whether a given number is a prime


number or not.
Pseudocode PRIME
{

read n
flag= 1
i=2
while i <= n/2
{
if remainder of n/i == 0
{
flag = 0
exit loop
}
i= i+1
}
If flag == 0
{
print is not a prime number.

17
}
Else
{
print prime number.
}
}

1.4.4 Flowchart

A flowchart is a graphical representation of an algorithm using a set of standard


symbols. It helps in the visualization of steps to solve a problem. Based on the fact that a
picture is worth a thousand words, we quickly grasp the information presented to us in a
graphical form compared to the text form. Programmers widely use flowcharts to crystalize
the logic of a program before writing the program. Table 1.3 lists the commonly used
symbols in flowcharts with a brief description of each.

Table 1.3: Commonly used flowchart symbols

Symbol Name Description


(Shape)
Flowline It shows the sequence/flow of execution of connected
(Arrow) blocks. Execution flows in the direction of the
arrowhead.

Terminal It represents the start or the end of a flowchart.


(Oval)
Process It represents imperative statements, i.e.,
(Rectangle) programming statements which processesdata and
producs results.

Decision It shows a decision point at which the execution flow


branches in different flow directions based on some
(Diamond) condition. It is also called branching operation, where
the execution flow can choose a path out of different
paths based on some criterion.

18
Input-Output It represents input or output operations, i.e., reading
(Parallelogram) or writing data from/to input/output devices.

On-page A pair of on-page connectors remotely connect two


Connector blocks on the same page of a flowchart. It reduces the
clutter of flowlines.
(Circle)

Off-page A pair of off-page connectors connect two blocks on


Connector two different pages of a long multipage flowchart.

1.4.5 Examples of Flowcharts

Following are the flowcharts of the algorithms given in section 1.5.2.

19
Example 1.7: A flowchart to add two numbers entered by the user.

Start

Read num1, numb2

Sum=num1 + num2

Print sum

Stop

20
Example 1.8: A flowchart to find the largest number among three different
numbers.

Start

Read a, b, c

yes no
a>b
no no
a>c b>c
yes yes
x=c
x=a x=b

Print x

Stop

21
Example 1.9: A flowchart to find roots of a quadratic equation ax2 + bx + c = 0.

Start

Read a, b, c

d = b2-4ac

yes no
d >= 0

r1 = (- rp = -b/2a
r2 = (-b- -d)/2a

Print r1, r2 Print rp, ip

Stop Stop

22
Example 1.10: A flowchart to calculate the factorial of a number entered by
the user.

Start

Read n

factorial=1
i=1

factorial= factorial * i
i=i+1

yes
i<n
no
Print

Stop

23
Example 1.11: A flowchart to check whether a given number is a prime
number or not.

Start

Read n

flag=1
i=2

reminder= mod (n, i)


i=i+1

yes
Is reminder =0?
no flag=0
yes

Is i<=n/2?
no

no yes
Is flag =1?

Stop

24
1.4.6 Python Programs

Following is a Python program that finds out whether a given number is a prime
number or not. The program implements the flowchart shown in example 1.11. Readers
may skip this section as the basic syntaxes of Python are introduced in chapter 2. However,
it shows that a Python program is easy to understand as it is very near to a natural language.
This feature makes Python a popular programming language.

Example 1.12: A Python program to test a given number whether it is prime


or not.
#Find out if the given number is a prime or not
#Read the number to be tested
n =int(input("enter an integer number:"))
#Initialise the variables
flag=1
i=2
while(i<n//2):
if n%i == 0: #Test for divisibility
flag=0
break
i=i+1
if flag== 1: #Prime, if no divisor is found
print(n, " is a prime number ")
else:
print(n, " is not a prime number")

Output

enter an integer number:20


20 is not a prime number

enter an integer number:31


31 is a prime number

25
Chapter Summary

1. A computer is an electronic machine used for storing, organizing, and finding


words, numbers, and pictures, doing calculations, and controlling other
devices.
2. A computer system has two main components: hardware and software
3. Input devices are used to read data
4. Output devices are used to display information
5. The central processing unit (CPU) is the brain of a computer. It consists of
ALU, CU, and memory.
6. Computer memory is any physical device where data/information and
programs are stored and retrieved when required.
7. Computer software is an ordered set of instructions executed on a computer
to perform a particular task or function.
8. The software is classified as system software or application software.
9. System software is used to operate and manage a computer, such as file
management and memory management, executing a program, mangaging
input and output devices.
10. Application software is used to perform a user's specific task, such as writing
a letter, designing an image, and creating a drawing.
11. A computer programming language is used to create/modify programs.
12. A compiler is a program that converts the complete source code written in a
high-level language into an executable program.
13. An interpreter is a program that converts and executes a high-level source code
into executable codes, line-by-line.
14. An algorithm is the problem-solving steps of a task written in a natural
language, whereas a flowchart is a graphical representation of the problem-
solving steps.
15. A program consists of imperative statements, conditional statements, and
iterative statements.

Multiple Choice Questions

1. Which of the following cannot be performed by a computer?


(a) Store information
(b) Perform calculation
(c) Control other machines
(d) None of the above

26
2. Which of the following is not a part of a computer?
(a) CPU
(b) Memory
(c) Input device
(d) None of the above
3. Which of the following is an input device?
(a) Printer
(b) Speaker
(c) joystick
(d) Monitor
4. Which of the following is not an output device?
a) Printer
(b) Speaker
(c) Camera
(d) Monitor
5. Which of the following is not a part of the CPU of a computer?
(a) ALU
(b) CU
(c) Register
(d) RAM
6. Which of the following is not a permanent memory?
(a) RAM
(b) ROM
(c) Hard disk
(d) Flash memory
7. Which of the following is not a system software?
(a) Windows
(b) Linux
(c) Notepad
(d) Unix
8. Which of the following is an application software?
(a) MS Word
(b) Tally
(c) AutoCAD
(d) All of the above

27
9. Which of the following is not performed by the operating system of a
computer?
(a) File management
(b) Memory management
(c) Handling input devices
(d) Write a letter
10. Which of the following is not a programming language?
(a) C++
(b) Java
(c) Python
(d) Linux
11. Which of the following is not an operating system?
(a) Linux
(b) Windows
(c) Unix
(d) None of the above
12. Which of the following is a utility software?
(a) WinZip
(b) CCleaner
(c) Partition wizard
(d) All of the above
13. Which of the following is not a high-level programming language?
(a) C++
(b) Python
(c) Java
(d) None of the above
14. Which of the following is a low-level program?
(a) Python program
(b) BASIC program
(c) Java program
(d) Assembly program
15. Which of the following is a compiled programming language?
(a) C++
(b) Python
(c) PHP

28
(d) None of the above
16. Which of the following is not an interpreted Programming language?
(a) C++
(b) Python
(c) Java
(d) Ruby
17. Which of the following is an intermediate programming language?
(a) C++
(b) Java
(c) Python
(d) FORTRAN
18. Addition of two numbers is _____________.
(a) an imperative statement
(b) a conditional statement
(c) an iterative statement
(d) None of the above
19. Choosing a flow path based on the comparison of two numbers is
_____________.
(a) an imperative statement
(b) a conditional statement
(c) an iterative statement
(d) None of the above
20. Repeating a block of code for n times is _____________.
(a) an imperative statement
(b) a conditional statement
(c) an iterative statement
(d) None of the above

Review Questions

1. State whether the following statements are true or false:


a. A computer is an electric machine.
b. CPU is a hardware.
c. Registers are part of a CPU.
d. A scanner is an output device.
e. The CPU consists of ALU, CU, and registers.
29
f. RAM is a volatile memory.
g. MS Word is a system software.
h. Python is a compiled programming language.
i. Java is a compiled programming language.
j. Linux is a programming language.
k. Python is a low-level programming language.
l. Circles are used as on-page connectors in a flowchart.
m. Ovals are used as terminals in flowcharts.
n. Rectangles are used as input in flowcharts.
2. Draw a block diagram of a computer and discuss the roles of its various
components.
3. Describe different types of computer software.
4. Compare application and system software.
5. Describe types of system software.
6. Describe levels of computer programming languages.
7. Describe the advantages and disadvantages of machine language.
8. Describe the advantages and disadvantages of a high-level language.
9. Differentiate between an Interpreter and a Compiler.
10. Describe commonly used symbols in flowcharts.

Programming Exercises

1. Write an algorithm and draw a flowchart to input two numbers, a and b,


and print any one of the following string based on the values of the

2. Write an algorithm and draw a flowchart to find the volume of a cuboid.

3. Write an algorithm to find the sum of digits of a number.

4. Write an algorithm and draw a flowchart to calculate the hypotenuse of a


right-angled triangle.

5. Write an algorithm and draw a flowchart to calculate the distance


between two points, p1(x1, y1) and p2(x2,y2).

30
6. Write an algorithm and draw a flowchart to read the distance d (in
kilometer) traveled by a vehicle in time t ( in minutes) and calculate the
vehicle's speed in m/s.

7. Write an algorithm and draw a flowchart to find the minimum of three


given numbers.

8. Write an algorithm and draw a flowchart to print a multiplication table of


a given number.

9. Write an algorithm and draw a flowchart to read marks obtained in three


subjects by a student and the maximum mark in each subject. Calculate
the student's total marks and percentage.

10. Write an algorithm and draw a flowchart to find the sum of the first N
natural numbers.(Hint: sum=n*(n+1)/2)

11. Write an algorithm and draw a flowchart to find the last digit of a number.
(Hint: divide the given number by 10 and multiply the quotient by 10 and
subtract the original number).

31
32
Chapter 2

Overview of Python
Learning Outcomes
1. Identify some domains where Python is widely used.
2. Install and run the Python interpreter.
3. Create and execute Python programs using IDLE
4. Describe the basic structure of a python program

Python is an interpreted, object-oriented, high-level, general-purpose programming


language. It is very popular due to its simple programming syntax, and English-like
programming statements. Further, due to fewer syntactical constructions and the use of
common English words, Python codes are easy to understand, learn, and maintain. It
does not use complex punctuations as compared to other languages. Further, it has high-
level built-in data structures, such as lists, sets, dictionaries, and it supports dynamic
typecasting and dynamic binding. These features make it an attractive option for rapid
application development, scripting, and automation. Python supports modular
programming through packages. Packages also help reuse the codes.

Python is a free and open-source programming language available for all major
computing platforms and operating systems. Further, it has a large set of free standard
libraries. Since it is an interpreted language, the edit-test-debug cycle is incredibly fast.
Easy debugging of Python programs is also another significant advantage of Python.
Python supports source-level debugging that allows inspection of local and global
variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the
code a line at a time, and so on. Due to these features, Python is the widely used
programming language.

2.1 History of Python


Python is conceptualized and developed by Guido van Rossum at the National
Research Institute of Mathematics and Computer Science, the Netherlands, in the late

33
1980s. It is designed as a sequel to the ABC programming language, with exception
handling capability. The name Python is taken from the British TV show Monty Python.

Similar to other languages, Python evolves through several versions. In 1991, the
first version of Python, Python 0.9.0, was released. The first version included features
such as exception handling, classes, lists, and strings. In addition, it had lambda, map,
filter, and reduce, which made it suitable for functional programming.

In 2000, the second version, Python 2.0, was released as an open-source project and
included list comprehensions, a full garbage collector, and support for Unicode.

In 2008, Python 3.0 was released. The major noticeable change was the way the print
statement works in Python 3.0. The print statement of Python 2.0 was replaced with the
print () function in Python 3.0.

2.2 Why Python?


There are many languages, such as C, C++, C#, Java, Visual Basic, JavaScript, PHP,
Python, currently available for various programming tasks. Each language has its own
strength and is suitable for different programming tasks. The popularity of Python is
due to the following major reasons:

1) Easy to learn and use

Python is one of the easiest programming languages to learn and use due to:

its simple syntaxes and punctuations.

its use of constructions similar to the English language.

These features also make the Python code readable and easy to maintain and reuse.

2) Support from large software companies and academics

Python Programming language is supported by many large software companies,


such as Facebook, Amazon Web Services, and Google. Python is also widely used as the
core programming language in schools and colleges across the globe. Most universities
use Python for research in Machine learning, Artificial Intelligence, Deep Learning, and
Data Science.

34
3) Maturity and vast support of libraries

Python is a very mature language as it is widely used for more than 30 years.
Further, over the years, a large collection of libraries is now available at no cost. Plenty
of learning materials, such as documentation, guides, and video tutorials for Python
language, are available to programmers. Hundreds of Python libraries and popular
frameworks are available due to corporate sponsorship and a large community of
Python developers. These libraries and frameworks save time and efforts in the software
development cycle. In addition, many specialized libraries, such as nltk for natural
language processing, scikit-learn for machine learning applications, are available for
research in emerging areas of development. Further, there are libraries for the
commonly used tasks, such as Matplotib for plotting charts and graphs, SciPy for
engineering, scientific and mathematical applications, BeautifulSoup for HTML and
XML parsing, NumPy for scientific computing, and Django for server-side web
development.

4) Portability and Versatility

Python is platform-independent, i.e., the same program runs on all operating


systems and different types of machines. It is also very versatile, i.e., it can be used for
developing different types of software, such as mobile applications, desktop
applications, web development, hardware programming.

5) Support for emerging research areas

Python is widely used in the emerging areas of computer science, such as cloud
computing, machine learning, neural network, data science, and big data. Leading
universities and research centers use Python to carry out research and development in
the above emerging areas.

6) Software integration

Python code can easily use libraries developed in other programming languages,
such as C, C++, and Java. This feature makes it very easy to extend the capabilities of a
python program and reduces the development cycle.

2.3 Installing Python

35
Python is available for almost all operating systems, such as Windows, Linux, Mac.
We can download the latest version and older versions of Python for any platform freely
from [Link]/downloads. Python is preinstalled on most Linux distributions.
Following is a step-by-step instruction to install the latest version of Python on the
Windows operating system.

Step 1: Download the latest version of Python for windows from the
[Link]/downloads website. The older versions of Python are also available
on the same website.

Step 2: Double click the downloaded installer (such as [Link]) to start


the installation process. A pop-up window of the installer will appear, as shown in
figure 2.1. Next, check the two checkboxes given at the bottom of the pop-up (install
launcher for all users (recommended), and Add Python 3.7 to PATH) to ensure
availability of Python to all the users, and the PATH environment variable is modified
to access Python from anywhere.

Figure 2.1: Python Installer pop-up window

36
If the Python Installer finds an earlier version of Python installed on your computer,
the installer will give the option to upgrade to the latest version or install the latest
version separately.

Step 3: Click the Install Now (or Upgrade Now) message to start the installation. Click
Yes to the message "Do you want to allow this app to make changes to your device" to
begin the installation. Figure 2.2 shows the installation progress window. It will show
the various components it is installing, and finally, a pop-up window will appear saying
that "Setup was successful", as shown in figure 2.3.

To verify that Python is installed on your computer, open the command prompt and
type python; you will see a window, as shown in figure 2.4, telling the version and other
details. We can open a command prompt window by any one of the following options:

(1) Right-click the Start button and choose Command Prompt (or PowerShell)
(2) Press Windows key + X, followed by C (non-admin) or A (admin)).

Figure 2.2: Python installation progress window

37
Step 4: Click the close button. Python is now installed on your system.

Figure 2.3: Python installation successful window

Figure 2.4: Running Python from the command prompt

38
2.4 Starting Python in Windows
Once Python is installed, we can use Python in two ways: Python command prompt
and Python IDLE.

2.4.1 Python Command Prompt

The Python interpreter starts running when we enter python


command prompt. Figure 2.5 shows the Python command prompt window. The Python
command prompt (>>>) is ready to execute Python codes. We can directly type a Python
statement at the prompt, and by pressing the enter key, the interpreter runs the
statement and produces the results. This interactive mode of the Python interpreter can
be used as a very powerful scientific calculator. For example, figure 2.5 shows how to
use the Python command prompt to evaluate the expression 10+15*3+2/3, and write a
program to add two numbers. However, the Python command prompt is not widely
used for writing programs in this fashion.

In practice, we write a Python program in an editor and run it to solve a problem. A


Python program (also called script) is a text file, and it can be created in any plain text
editor, such as notepad. We can run a program by passing the name of the program as
an argument to the interpreter. For example, the command to execute a Python program
([Link]) saved in the folder c:\users\MBM is C:\Users\MBM>python
c:\users\MBM\[Link]. Figure 2.5 shows the program and its output. If the file is in the
current folder from where the Python interpreter is executed, the command becomes
C:\Users\MBM>python [Link].

If the Python interpreter is not included in the PATH environment variable, we have
to specify the complete address of the interpreter, and the above command becomes as
given below:

C:\>C:\Users\MBM\AppData\Local\Programs\Python\Python39\python
c:\users\mbm\[Link].

Here, C:\Users\MBM\AppData\Local\Programs\Python\Python39\ is the


path of the Python interpreter, i.e., [Link] and c:\users\mbm\ is the path of the
program.

39
Figure 2.5: Writing Python program at the command prompt

Program [Link]

Figure 2.6: Executing a Python program at the windows command prompt

40
2.4.2 Python IDLE

A Python program can be written in any text editor, such as notepad, and can be
executed directly from the command prompt, but it is not a very convenient way to
write large programs. Therefore, most programmers use integrated development
environments (IDE), such as IDLE, VS code, Spyder, PyCharm. These IDEs provide
integrated facilities to create, edit, debug and execute a program. Most of the IDEs are
freely available. We can download an IDE of our choice from its website and install it
on our computer (More information about IDE is given in section 2.10).

In this book, we are using IDLE for creating and testing Python programs. Python's
Integrated Development and Learning Environment (IDLE) is installed by default when
we install Python. IDLE can create, modify, and execute Python programs and executes
a single statement in the interactive mode.

We can start IDLE like any other windows program from the start menu or search it
and click its icon. Figure 2.7 shows an IDLE window and it is called the IDLE Shell. The
IDLE Shell is similar to the Python command prompt and allows users to run Python
statements at its prompt. The interactive mode of IDLE is suitable for small Python
programs. But as the complexity and size of a program increases, it becomes difficult
and cumbersome to work in this mode. Therefore, for writing large programs, IDLE
provides an integrated programming editor. We can start the editor from the File menu
of the IDLE shell (File->New File) or using the shortcut command Ctrl + N, as shown
in figure 2.8. Creating a program in the editor is called script mode programming.

The IDLE editor has all the facilities to create, edit, save, open, run and debug a
program in an integrated environment. Figure 2.9 shows an editor window. The default
name of the new program is untitled. It is recommended to give a suitable name to a
program and save it before executing it.

To run the current program from the editor, use Run->Run Module, or F5 key, from
the drop-down menu of the editor (figure 2.10). The output of the program is shown in
the Python Shell, as shown in figure 2.11.

41
Figure 2.7: IDLE Shell

Figure 2.8: Starting the script editor in IDLE

42
Figure 2.9: Script editor

Figure 2.10: Running a script in the editor

Figure 2.11: Output of the script shown in IDLE Shell

43
2.5 Structuring Python Programs
One of the main reasons for Python's popularity is the simple syntaxes and
structures used to create Python programs. This section describes the proper structuring
and formatting of python programs.

2.5.1 Python Statements

It is a common practice to write one python statement in one line, and the 'new line
character' terminates the statement. However, it is possible to write more than one python
statement in a single line separated by semicolons, but it is not recommended, as it reduces
the program's readability. Example 2.1 shows a simple program that uses multiple
statements in a single line. Example 2.2 shows a preferred way of writing the previous
program.

Example 2.1: Multiple statements in a single line

# It is a bad Practice to write multiple lines in a single line


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

Example 2.2: A preferred way of writing Example 2.1

# It is a good Practice to write one statement in one line


# It increases the readability of a code
a = 10
b = 20
c = b + a
print(a)
print(b)
print(c)

44
2.5.2 Line Continuation

Some statements may be very long, and to view them, the programmer has to scroll
the screen left and right frequently. A lengthy statement can be broken into multiple lines
using line continuation to avoid scrolling and enhance readability. Python supports two
types of line continuation: implicit and backslash.

The implicit line continuation is automatically used in a statement containing


opening parentheses ('('), brackets ('['), or curly braces ('{'). In such a statement, the Python
interpreter treats the statement incomplete till it finds the matching closing bracket
corresponding to an opening bracket, even if the statement spreads across multiple lines. In
this situation, newline characters before the closing bracket are not treated as the statement
terminators, and the statement may continue to many lines. The same is true for
parentheses, square brackets, and curly braces, also. Example 2.3 demonstrates some multi-
line statements written at the IDLE command prompt. The implicit line continuation can be
used in scripts also.

Example 2.3: Implicit line continuation

>>> a=(1+
2+
3+
4)
>>> print(a)
10
>>> b=[1,
2,
3,
4,
5]
>>> print(b)
[1, 2, 3, 4, 5]
>>> c={'a':1,

45
'b':2,
'c':3
}
>>> print(c)
{'a': 1, 'b': 2, 'c': 3}

In explicit line continuation, a backslash (\) at the end of a line indicates that the
current statement is incomplete and continues to the next line. The explicit line continuation
is typically used when implicit line continuation is not applicable, such as a long expression
without brackets. Example 2.4 shows an example of explicit line continuation.

Example 2.4: Explicit line continuation

>>> a=1\
+2\
+3\
+4
>>> print(a)
10

2.5.3 Comments in Python

Comments are lines in a program that the interpreter ignores and are primarily used
to document the code properly. They greatly help in code readability and make code
maintenance and reuse very easy. In addition, we can use a comment to explain the purpose
and logic of a statement or a block of code. We can write comments throughout a program.

Python supports both line comment and block comment. To comment a single line
of text till the end of the line, we put a hash (#) character at the beginning of the text. The
line comment can begin from the start of a line (for example, #This whole line is a
comment) or start after a statement (for example, x=10 #This part of the line is a comment)
and continues until the end of the line. If we want to comment more than one line as
comments, we have to put a hash character at the beginning of each line. Please note that a

46
hash (#) inside a string does not make the text after it a comment, for example, x="In this
string, #this part is not a comment".

Python uses a pair of triple-double quotation marks (""") to create a multi-line string
literal. If we do not assign such a string to a variable, it can be used as a multi-line block
comment. Instead of a pair of triple-double quotation marks, we can also use a pair of triple-
single quotation marks (''') to create a block comment.

Please note, we begin a block comment from a line without any indentation, i.e.,
before the beginning triple-double quote, nothing is allowed, not even white spaces. In
contrast, a line comment can begin anywhere in a line and can have white spaces or any
other Python statement before the # mark.

Example 2.5: Comments in Python

# This is a line comment as it starts with #.


# Comments will be ignored by the interpreter
#Initialize a with 10
a=10
#Initialize b with 20
b=20

"""Start of a block comment


Anything written up to the next triple quotation marks
will be ignored by the interpreter.
End of the block comment"""
#Sum a and b
c=a+b

#Show result
print(c)
x="The part after # is not a comment as it is\
inside a string"
y='The portion between """ is not a comment """" \

47
as it is inside a string'
print(x)# print the value of x
print(y) # print the value of y
#End of program

Output
30
The part after # is not a comment as it is inside a string
The portion between """ is not a comment """" as it is inside a string

2.5.4 Proper Indentation

Python has straightforward syntaxes and uses indentations to form blocks.


Indentation is the process of adding white spaces before a statement. Python uses spaces
and tabs for indentation and newline characters as line terminators. Tabs and spaces can be
mixed to give indentation, but all the statements in a block must have an identical and
consistent indentation. The first executable block (the block of a program from where the
execution begins, also called the main block) cannot have any indentation. Adding
indentation to the main block will raise an indentation error, "Syntax error: unexpected
indentation". At the command prompt, no white spaces are allowed at the beginning of a
statement. Again, attempting to give white spaces at the beginning of a statement will raise
the error "Syntax error: unexpected indentation". However, whitespaces may be included
inside a statement. The inside and trailing spaces in a statement are not an error and are
ignored by the Python interpreter. For example, the statement a=10 + 20 * 5 has a few
spaces inside it. The interpreter removes these spaces, and the previous statement is
equivalent to a=10+20*5. Programmers are encouraged to use white spaces freely to
increase the readability of programs. Example 2.6 shows some uses of correct and incorrect
indentations in a program.

Example 2.6: Indentation in Python

a=10 #Error: as the first block cannot have any indentation


b=20
c=int(input("Enter a number"))

48
if c <10:
print(a+b) #Properly indented block
print(a*b)
else:
print(a-b)
print(a/b)

#The following indentation will raise error


if c <10:
print(a+b) #incorrect indentation
print(a*b)
else:
print(a-b)
print(a/b) #incorrect indentation

2.6 Structure of a Python Program


A typical Python program consists of many sections: documentation sections,
import sections, function definitions, and the main program. Figure 2.4 shows a typical
structure of a Python program. All sections may not be present in every program. Though
documentations are not an essential part of a program, it is considered an important part of
it as it enhances the readability and comprehension of a program. The inclusion of
documentation is in line with the famous quote, "Codes are more often read than written".
This quote highlights the importance of documentation. Documentation becomes more
important in open source development as many people across the globe will use your code.

A Python program can seamlessly include and use the codes written in other python
programs. The import statement is the primary mechanism to include codes from other
Python scripts. Though import statements can be written anywhere in the program, they
must be written before using the imported code. However, writing import statements at the
top of a program tells the program's dependencies on other modules. Hence, it is a
recommended approach.

49
The function declaration section defines functions used in a program. A function
definition must appear before the use of the function.

The main block of a program is coded with no indentation. The program execution
begins from the first statement of the main block. The main block codes may not be
contiguous. It can be written in many segments. For example, we can write a function block,
then a part of the main block, another function block, and the other part. Example 2.7 shows
the above concepts with an example.

Documentation section

Import section

Function definitions

Main program

Figure 2.4: Typical structure of a Python program

Example 2.7: Typical structure of a Python program

#Documentation section
"""
Script Author: Arvind
Organization: MBM Engineering College, Jodhpur, India
Date: 10 December 2020
Version: 1.0
Purpose: Print the largest of three randomly generated numbers
"""

#import section
#importing the random module to include random number
#generator functions
import random

50
#Function section

#Function to find the largest of three numbers

def largest(a, b, c):


if a> b :
if a> c:
large=a
else:
large=c
else:
if b > c:
large=b
else:
large=c
return large
#End of the function

#main program section

x=[Link](10,100)
y=[Link](10,100)
z=[Link](10,100)
print("The largest of (",x,",",y,",",z,") is ",largest(x,y,z))

2.7 Coding Style


A program implements logic and steps to solve a problem and can be written in various
ways. If each programmer follows a different style to write a program, it becomes
challenging to maintain the program in the long run. Further, it reduces the readability of a

51
program. To overcome these difficulties, the Python coding style PEP 8 is widely used by
most Python programmers. This style is not a set of rules but a set of customs that help write
more readable and consistent codes. Following are the most important points of the PEP 8
style:

Use 4-space indentation. Use of tabs is not recommended.

Use docstrings. A docstring is the first block comment string written after the function
header or written at the beginning of a module. Python uses the docstring of a
module/function for automatically generating the help of the function/module.

Limit the number of characters in a line to less than 80 characters. This limit helps view
a program without using a horizontal scroll and correctly print a program on a paper.
lines using
line continuation mechanisms.

Use comments to explain the purpose and logic of the code. Comments should form
complete sentences and should be meaningful to the code.

-8 or ASCII encodings for writing programs. These encodings


make programs portable internationally. UTF-8 is a Unicode-based encoding system to
accommodate characters of most of the natural languages.

Use spaces around operators and after commas to enhance readability.

Use a consistent naming convention. For example, refer to the naming convention
section 2.8 below, which describes a widely used naming convention.

-ASCII characters in identifiers, as this reduces code reusability and


creates problems in code maintenance.

2.8 Identifier Naming Convention


Identifiers are names used to identify different entities in a program, such as variables,
functions, classes, constants, modules. Following are the general recommendations to name
identifiers in Python:

Use relevant names instead of generic names. For example, use student_list,
class_list instead of list1, list2.

52
Avoid using similar-looking characters as single-characters identifier names. For
example, (lowercase letter el) and (uppercase letter eye) confuse with 1.
Similarly, (uppercase letter oh) confuses with zero.

Avoid using very wordy names, such as


dictionary_for_the_purpose_of_storing_data. The wordy names increase typing
time and cause errors.

Following are the specific conventions to be used to name different types of objects in
Python:

Packages and modules: Use all lower case letters to name a package/module. For
multiple words package names, use an underscore to separate each word. However,
a single-word package/module name is preferable, for example, numpy, sklearn,
sklearn.linear_model.

Classes: Use camelCase to name a user-defined class. In camelCase, the first letter
of the first word in the identifier name is in the lower case, while the first letter of
every subsequent word is in the uppercase. Further, use only the English alphabets
in a class name; avoid using numerals, underscore, and special symbols. In Python,
all the built-in classes are in lowercase words, except the Error class.

Variables and methods: Use lowercase to name variables/methods. A multiple


word variable/method name should be separated by an underscore (_). Private
variables/methods begin with a single underscore. A double underscore prefix is
used to name attributes/methods in a class.

Constants: In Python, there is no symbolic constant. However, we use variables


with all capital letter names to indicate that these variables be treated as constants
by programmers, such as PI=3.14. Use a single underscore to separate multi-word
constants, such as GRAVITY_CONSTANT=9.81.

2.9 Python Implementations


Another reason for the popularity of Python is that it is available for almost all digital
devices, from computers to micro-controllers, through its various implementations. Various
implementations are implemented differently as per the requirements but use the same
syntax. Following is a brief description of major implementations of Python. Interested
readers can explore the website of a particular implementation for a detailed description.
53
Cpython: The default implementation of Python is CPython. CPython, written in a
mixture of C and Python, has a large standard library. As a result, CPython is the
most popular and widely used implementation. It is also called traditional Python.
CPython can be defined as both an interpreter and a compiler as it compiles Python
code into bytecode before interpreting it.

IronPython: IronPython is an open-source Python implementation using C# and is


integrated with the .NET Framework. This integration helps use of .NET Framework
and Python libraries and facilitates other .NET languages to use Python code easily.

Jython: Jython is a Java implementation of Python and can be used on any platform
with a JVM installed. Jython has an interactive interpreter that can interact with Java
packages as well as running Java applications. This interactive interpreter makes it
a rapid application development tool and helps seamless interaction between
Python and Java.

PyPy: PyPy is another Python implementation using Python itself and uses just-in-
time (JIT) compilation. It is said to be 7.5 times faster than CPython. In JIT
compilation, the source codes are compiled directly to the native machine code,
making it very fast.

Stackless Python: Stackless Python is another implementation of Python that does


not use the C call stack for its own stack. This change in stack management strategy
allows the main thread to run hundreds of thousands of tiny tasks, called tasklets.
Tasklets run completely decoupled and communicate through channels. Thus,
Stackless Python allows thread-based programming without compromising
performance and complexity problems as found in conventional thread
programming.

2.10 Python IDEs


Python programs can be written in any text editor. However, many integrated
development environments (IDEs) have been developed that make writing Python code
and its maintenance much easier. The commonly used IDEs are IDLE, Spyder, PyCharm,
Sublime, Emacs, Atom, and VS Code. These IDEs provide facilities to write, edit, format,
debug, execute, and test programs. However, it is strongly recommended to use IDLE for
beginners. Interested readers can explore the respective websites for detailed features of
various IDEs. All codes in this book are written in IDLE. IDLE is installed by default with

54
standard Python. The two popular editors are described next, for others, refer their websites
for their features.

PyCharm, developed by JetBrains, is another popular IDE used for the Python
programming language. It provides code analysis, a debugger, and supports web
development with the Django web framework. It is cross-platform and available for
Windows, MacOS, and Linux. The Community Edition is freely available and can be
downloaded from the link [Link]

Jupyter Notebook is a browser-based web application that can be used as an IDE


for Python programming. It provides facilities to create, modify and execute Python
programs. A unique feature of Jupyter is mixing of formatted text and mathematical
expressions with the programming codes. For mixing, it uses two types of cells: code cell
and text cell. Code cells are used to write codes, whereas text cells are used to write plain
texts. On executing a code cell, the output is written just below the cell. This integration of
code, plain text, and output in a single page is very convenient for scientific computing. The
Jupyter notebook is installed with the Anaconda Python distribution.

2. 11 Python Distributions
As already stated, Python is a general-purpose programming language that is
widely used for many tasks, such as data science, machine learning. However, the standard
Python installation may not be suitable for different tasks as it frequently requires installing
dependent packages from scratch. Several tools and utilities are freely available to manage
packages easily, called distributions. A Python distribution is a bundle that contains a
Python implementation along with a bunch of libraries, tools, and IDEs. Popular Python
distributions are Anaconda, Enthought Canopy, ActiveState, and Intel. We can install
multiple Python distributions on a single system and use them independently as per our
requirements.

Anaconda is a free and open-source Python distribution widely used for data science
and machine learning applications. It uses conda as its package manager. Anaconda is pre-
bundled with popular data science and machine learning software libraries, such as Scikit-
learn, Keras, PyTorch, TensorFlow, SciPy, and many other popular data science packages
suitable for Windows, Linux, and MacOS. It also includes two popular IDEs, namely,
Spyder and Jupyter notebook for writing and executing Python programs. We can
download the Anaconda Individual Edition distribution from
[Link] For other distributions, interested readers may
refer to their websites.
55
Chapter Summary

1. Python is an interpreted, object-oriented, high-level, general-purpose


programming language.
2. Python is a free and open-source programming language available for all major
computing platforms and operating systems.
3. Guido van Rossum developed Python at National Research Institute of
Mathematics and Computer Science, the Netherlands.
4. Python supports both line and block comments. A line comment begins with #
and continues till the end of the line. A block comment begins with a triple-double
quote and ends with a triple-double quote. A block comment can contain multiple
lines. We can also use triple-single quotes in place of triple-double quote.
5. Python uses indentation to create a block inside another block.
6. IDLE, PyCharm, Jupyter, VS Code, and Spyder are popular integrated
development environments for Python programming.
7. A Python distribution is a bundle that contains a Python implementation and a
bunch of libraries, tools, and IDEs. Popular Python distributions are Anaconda,
Enthought Canopy, ActiveState, and Intel.
8. Anaconda is a free and open-source Python distribution widely used for data
science and machine learning applications.

Multiple Choice Questions

1. Which of the following is not true about Python?


(a) It is an object-oriented programming language.
(b) It is a high-level programming language.
(c) It is a compiled programming language.
(d) It is a general-purpose programming language.
2. Python is popular because of the following reason:
(a) Simple syntax
(b) Built-in high-level data structures
(c) Support for Unicode characters
(d) All of the above

56
3. Python is initially developed by
(a) Charles Babbage
(b) Guido van Rossum
(c) Dennis Ritchie
(d) Larry Wall
4. Which of the following can be used to write a Python program?
(a) IDLE
(b) PyCharm
(c) Spyder
(d) All of the above
5. Which of the following is not a Python distribution?
(a) Anaconda
(b) Enthought Canopy
(c) ActiveState
(d) None of the above
6. The default package manager of Anaconda distribution is
(a) conda
(b) Spyder
(c) Jupyter
(d) pip
7. Which of the following IDE is installed by default with Python?
(a) IDLE
(b) VS Code
(c) Spyder
(d) Jupyter
8. Which of the following character is used to start a line comment?
(a) #
(b) /
(c) %

9. Which of the following is valid to start a block comment?


(a) """
(b) %
(c) #
(d) None of the above

57
10. Which of the following character is used to separate multiple statements in a
line?
(a) comma
(b) Semi-colon
(c) Colon
(d) Space
11. Which of the following character is used to separate multiple expressions?
(a) comma
(b) Semi-colon
(c) Colon
(d) Space
12. Which of the following character is used to continue a statement to the next
line?
(a) Backslash
(b) Forward slash
(c) Colon
(d) Space
13. Which of the following function key is used to run a script in IDLE?
(a) F5
(b) F6
(c) F7
(d) F8
14. Which of the following shortcut key is used to open a new script?
(a) Ctrl+O
(b) Ctrl+S
(c) Ctrl+N
(d) Ctrl+P
15. Which of the following is the default name of a script in IDLE?
(a) script
(b) nonename
(c) untitled
(d) None of the above

58
Review Questions

1. State whether the following statements are true or false:


a. Python is an interpreted programming language.
b. Python does not support object-oriented programming.
c. Python supports high-level data structures, such as lists, sets.
d. Python uses curly brackets to form blocks.
e. The name Python is taken from the British TV show Monty
Python.
f. In Python 3, print is a function, not a statement.
g. Python supports garbage collection.
h. Python does not support Unicode.
i. PyCharm is an IDE.
j. The default name of the new program is untitled.
k. F2 is the shortcut key to run a Python program in IDLE.
l. Jupyter is a Python distribution.
m. A Python statement must be written in only one line.
n. We can write more than one statements in a line.
o. A semi-colon is essential at the end of each line.
p. Hash character is used to write a comment.
q. Python does not support block comments.
2. Briefly describe the history of Python.
3. Describe the reasons for the popularity of Python.
4. Describe steps to install Python on your computer.
5. Describe the typical structure of a Python program.
6. Describe the coding style used for Python programs.
7. Discuss various Python implementations.
8. Discuss Python distributions.

59
60
Chapter 3

Basics of Python Programming


Learning Outcomes
1. Describe the Python character set, keywords, and datatypes
2. Explain tokens, identifiers, and delimiters in Python
3. Distinguish various types of literals
4. Perform input and output operations
5. Perform formatting of output
6. Perform conversion of one literal type into another type

Like any other high-level programming language, Python uses a set of symbols,
such as a, b, +, /, 1, 2, and keywords along with a set of syntax rules to write computer
programs. However, Python is very close to the English language in constructing its
statements, making it one of the most widely used programming languages. Further, it
uses fewer syntactic constructions and uses common English keywords, making Python
programs highly readable, easy to comprehend, and economical to maintain.

3.1 Character Set


Python 3.0 and newer versions support Unicode characters to name identifiers.
Unicode character encoding standard assigns a unique code to every character and
symbol of most human languages. Hence, a Python code and strings can have characters
from any combination of languages. However, it is strongly recommended to use ASCII
code characters to write a Python program to make it more portable and re-usable across
the globe. ASCII stands for American Standard Code for Information Interchange and
is a subset of Unicode. Example 3.1 shows a valid Python program that uses Unicode
characters (from Hindi and Greek letters) to name variables and functions. Although
Python allows Unicode to name identifiers, the character set (primarily based on the
English language) given in table 3.1 is preferred to write Python programs to promote
international portability, ease of maintenance, and reuse.

61
Most of the IDEs used to write programs using English keyboards do not have direct
facilities for typing all the Unicode characters. However, any Unicode character can be
easily included in a string using the escape character sequence \u+Unicode of the
For example, to create a string , in Python code, it is coded as
\u03b1\u03b2\
respectively.

Example 3.1: Use of Unicode(from Hindi and Grrek letters) in a Python program

>>> def ( , ):

return +

>>> =10

>>> =20

>>> print(" :", ( , ))

: 30

Table 3.1: Preferred character set for writing Python programs

Character types Description

Letters All English alphabets, both lower and upper case, i.e., A, B, C,

Digits 0,1,2,3,4,5,6,7,8,9

Special Symbols Comma (,), period (.), semicolon (;), colon (:), question mark
(?), apostrophe ('), quotation mark ("), exclamation mark (!),
vertical bar (|), slash (/), backslash (\), tilde(~), underscore(_),
dollar($), percent sign(%), ampersand (&), caret (^), asterisk
(*), minus sign(-), plus sign (+), opening angle bracket or less
than sign (<), closing angle bracket or greater that sign (>), left
parenthesis ((), right parenthesis ()), left bracket ([), right
bracket (]), left brace ({), right brace ( }), number sign (#).

62
White spaces Blank space, horizontal tab, newline, carriage return, form
feed.

3.2 Python Token


A token is the smallest unit of a computer program. They are the building blocks of
computer instructions and statements. Python tokens can be grouped into six categories
based on their purpose in forming statements(figure 3.1): keywords, identifiers, literals,
special symbols, and operators. Keywords are reserved words; identifiers are names of
variables, constants, functions, and packages; special symbols are delimiters; operators are
symbols to perform specific operations on data; and literals are fixed values used in the
source code. These are discussed in more detail later in the chapter.

Python Token

Keywords Identifiers Literals Operators Delimiters

Figure 3.1: Python tokens

3.3 Keywords
Keywords are reserved words for specific purposes to write Python statements, and they
, such as naming variables, functions, or any other
identifier. They are the building blocks of Python and are used to define the syntax and
structure of the Python language. Keywords are case sensitive in Python, and there are 33
keywords in Python 3. Table 3.2 lists all the keywords of Python 3.10 with a brief description
of each. In all, there are 35 keywords in Python 3.10. Please note, the number of keywords
may be different in different versions of Python. You can use the help () function in your
Python shell without any argument and then type a keyword to list the keywords in your
Python installation, as illustrated below.
63
>>> help()

Welcome to Python 3.9's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at [Link]

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

False break for not


None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield

Table 3.2: Python keywords

Keyword Description

and To perform logical AND operation

64
as To create an alias

assert To debug a code using an assertion condition.

async To declare an asynchronous function

await To asynchronously wait for a task to complete.

break To break further execution of a loop

class To define a class

continue To skip the remaining portion of the body of a loop and continue the
next iteration of the loop

def To define a function

del To delete an object

elif To form an else-if portion of a ladder if conditional statement

else To specify a block of codes to be executed when all specified


conditions are false in a conditional statement. It is also used in a
loop to execute a block of code on the normal termination of the loop.

except To specify what to do when an exception occurs

False To represent the Boolean FALSE value

finally To create a block of code that will always execute in a try-except


block

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

65
import To import a module

in To check if a value is present in a collection

is To test if two variables are referring to the same object

lambda To create an anonymous function

None To represent a null value

nonlocal To declare a non-local variable

not To perform logical NOT operation

or To perform logical OR operation

pass To create a null statement, i.e., a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True To represent the Boolean TRUE value

try To make a try-except statement for catching exceptions

while To create a while loop

with To automatically manage resources, such as files.

yield To write a generator function

3.4 Identifiers
An identifier is a sequence of characters used to name a variable, function, class,
module, or other objects. In Python, an identifier starts with an alphabet, preferably an
English letter, A to Z or a to z or an underscore (_), followed by zero or more letters,
underscores, and digits (0 to 9). Python is a case-sensitive language, i.e., upper case letters
66
are different from the lower case letters. Hence, Name, NAME, and name are different
identifiers.

3.4.1 Rules for Naming Identifiers

Following are the rules to name identifiers in Python 3.0:

1. An identifier name must contain only letters, digits, and underscore. The letter can
be from any human language. However, English letters are widely used and highly
recommended.
2. The first character of an identifier name must be a letter or underscore, i.e., an

3. A Python keyword cannot be used as an identifier name.


4. An identifier cannot have space or special characters, such as $, +, -, %.
5. An identifier can be of any length.

Examples of some valid identifier names are: a, B, Abc, var1, var_1, _var, _1var, my_list,
name_of_student. Please note, an underscore ( _ ) is a valid identifier name. Non-English
alphabets/words such as , , , , are some Hindi valid identifier names, and a,
b. d, m, l, p, ab are some Greek valid identifier names. Table 3.3 gives examples
of some invalid identifier names along with reasons.

Table 3.3: Examples of invalid identifier names

Invalid Identifier Description


names

1abc An identifier name cannot start with a digit (rule 2)

Sum of a and b An identifier name cannot have spaces (rule 4)

Sum$ An identifier cannot have special characters(rule 4)

lambda An identifier name cannot be a keyword (rule 3).


lambda is a keyword.

67
3.5 Literals and Their Types
A literal in a program is a constant value, such as 10, 25.5, 'abc', (1,2,3), that does not
change during the execution of a program. Python supports the following literal types: int,
float, complex, str, bytes, bool, NoneType, list, tuple, dict and set. Figure 3.2 shows a
classification of literal types of Python.

Python literals

String Numeric Boolean Collection None

Integer Float Complex

string bytes

List Tuple Set Dictionary

Figure 3.2: Python literals

3.5.1 String Literals

A string literal is a fixed text. In Python, a string literal is written using a pair of single
quotes ('), double quotes ("), triple single quotes ('''), or triple double quotes ("""), for
example,

'This is a single quote string literal',


68
"This is a double quote string literal",
''This is a triple single quote string literal''', and
"""This is a triple double quote string literal""".

There is no difference between a single quote and double quote literals. However, we
cannot start a literal with a single quote and end with a double quote, i.e., mixing single and

are used to
create formatted multiline strings. Python ignores a string literal that is not assigned to a
variable. Hence, triple quote multiline literals can be used to write comments in Python.
Example 3.2 illustrates the above concepts.

Example 3.2: Creating string literals

>>> a='This is an example of a single quote string literal'


>>> print(a)
This is an example of a single quote string literal
>>> b="This is an example of a double quote string literal"
print(b)
>>> print(b)
This is an example of a double quote string literal
>>> c='''This is an
example
of
multiline and formatted triple single quote
literal'''

>>> print(c)
This is an
example
of
multiline and formatted triple single quote
literal
>>> d=""" This is a

69
triple double
quote string literals"""

>>> print(d)
This is a
triple double
quote string literals

Python 3 literals, by default, use Unicode. Hence, Python can create string literals
containing any character from most human languages (e.g., English, Spanish, Japanese,
Arab, Hebrew, Hindi). Contrary to Python 2, Python 3 string literals are Unicode. Hence
there is no requirement of prefixing u before a string literal to make it a Unicode string
literal. For example, the Python 2.0 Unicode string literal u'abc' is written in Python 3 as
'abc'.

Any Unicode character can be inserted in a string literal by using escape sequence
\u followed by the four-digit hexadecimal code of the character. For example, The Python
equivalent of the string is "\u03b1\u03b2\u03b3", where 03b1, 03b2, and 03b3 are

Example 3.3: Unicode characters in string literals

>>> s1="Python 3 strings use Unicode by default. No need to prefix u"


>>> s2=u"Python 3 strings use Unicode by default. No need to prefix u"
>>> print(s1==s2)
True
>>> s3="\u03b1\u03b2\u03b3"
>>> print(s3)

70
By default, Python 3.0 string literals use the UTF-8 encoding system, and the literals
created are of type str. However, a string literal can be made byte string (uses only ASCII
chacracters) by prefixing it with b. The object type of byte string literals is bytes. We can get
the type of an object by the type () built-in function. For example, b"My String" is a byte
string. An str object can be converted into a byte object by the encode () method of the str
object. And, a byte object can be converted into an str object by the decode () method of the
byte object. String literals can be encoded using other encoding systems, such as UTF-16,
and decoded back by explicitly passing the coding system in the encode () and decode ()
functions. Example 3.4 illustrates the above concepts.

Example 3.4: String literals coding systems

>>> s1="Python 3 strings use UTF-8 coding for string literals"


>>> type(s1)
<class 'str'>
>>> s2=b"String literals can be made byte strings by prefixing with
b."
>>> type(s2)
<class 'bytes'>
>>> s3=[Link]()
>>> type(s3)
<class 'bytes'>
>>> print(s3)
b'Python 3 strings use UTF-8 coding for string literals'
>>> s4=[Link]()
>>> type(s4)
<class 'str'>
>>> print(s4)
String literals can be made byte strings by prefixing with b.
>>> s5=[Link]('UTF-16')
Traceback (most recent call last):
<pyshell#10>", line 1, in <module>
s5=[Link]('UTF-16')

71
UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x2e
in position 60: truncated data
>>> s5=[Link]('UTF-8')
>>> print(s5)
String literals can be made byte strings by prefixing with b.
>>> s6=[Link]('utf-16')
>>> print(s6)
b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00 \x003\x00 \x00s\x00t\x00r
\x00i\x00n\x00g\x00s\x00\x00u\x00s\x00e\x00 \x00U\x00T\x00F\x00\x008
\x00 \x00c\x00o\x00d\x00i\x00n\x00g\x00 \x00f\x00o\x00r\x00 \x00s
\x00t\x00r\x00i\x00n\x00g\x00
\x00l\x00i\x00t\x00e\x00r\x00a\x00l\x00s\x00'
>>> s7=[Link]('utf-16')
>>> print(s7)
Python 3 strings use UTF-8 coding for string literals

By default, a backslash (\) character and a few characters after it have special
meaning in a string literals. Table 3.4 lists commonly used such combinations along with
their brief descriptions. The backslash (\) is called the escape [Link], to change
this default behavior of backslash characters in string literals, Python supports the concept
of a raw string. In a raw string, Python treats a backslash (\) as a simple character instead
of an escape character. A raw string literal is created by prefixing a string literal with 'r' or
'R'. It is
Example 3.5 illustrates escape sequences, and Example 3.6 shows the concept of raw string.

Table 3.4: Escape sequences

Escape Description
Sequence
\\ To include a backslash (\) in a string
\' To include a single quote (') in a string
\" To include a double quote (") in a string
72
\a To include a bell sound in a string
\b To include a backspace character in a string
\f To include a form feed character in a string
\n To include a line feed character in a string.
\r To include a carriage return character in a string.
\t To include a horizontal tab character in a string.
\v To include a vertical tab character in a string.
\ooo To include a character with an octal value ooo in a string.
\xhh To include a character with a hex value hh in a string..
\N{name} To include a character that is identified by a name in the
Unicode database in a string.
\uxxxx To include a character with 16-bit hex value xxxx. Exactly
four hexadecimal digits are required in a string.
\Uxxxxxxxx To include a character with 32-bit hex value xxxxxxxx.
Exactly eight hexadecimal digits are required in a string.

Example 3.5: Python escape sequences

>>> print("\\ This is a backslash character")


\ This is a backslash character
>>> print("This string includes a single quote(\') character")
This string includes a single quote(') character
>>> print("This string includes a double quote(\") character")
This string includes a single quote(") character
>>> print("This string includes a bell sound(\a) character")
This string includes a bell sound() character
>>> print("This string includes a back space(\b) character")
This string includes a back space( ) character
>>> print("This string includes a form feed(\f) character")

73
This string includes a form feed() character
>>> print("This string is \nprinted in two lines")
This string is
printed in two lines
>>> print("This string is \rprinted in two lines")
This string is
printed in two lines
>>> print("In this string, a tab\tis inserted")
In this string, a tab is inserted
>>> print("This string is \vprinted in two lines")
This string is
printed in two lines
>>> print("Print ABC using octal codes \101\102\103")
Print ABC using octal codes ABC
>>> print("Print ABC using hexadecimal codes \x41\x42\x43")
Print ABC using hexadecimal codes ABC
>>> "Delta symbol is \N{GREEK CAPITAL LETTER DELTA}"

>>> "Alpha symbol is \N{GREEK SMALL LETTER ALPHA}"

>>> print("Print omega using 16-bit Unicode \u03A9")


Print omega using 16-
>>> print("Print omega using 32-bit Unicode \U000003A9")
Print omega using 32-

Example 3.6: Python raw strings

>>> print("This\tis\ta\tnormal\nPython string")


This is a normal
Python string

74
>>> print(r"This\tis\ta\traw\nPython string")
This\tis\ta\traw\nPython string
>>> print(r"In raw strings,\\ has no special meaning")
In raw strings,\\ has no special meaning

A string literal is stored in memory as an array of characters. Individual characters


can be extracted by using an index. For example, the expression 'abc' [0] will return the first
character of the literal. In Python, literals are immutable, i.e., once a literal is created, it
cannot be modified in the program. However, we can extract a part of the literal using the
indexing mechanism. Example 3.7 extracts a character from a string using an index.

Example 3.7: Extracting characters of a string

>>> print("The fourth character of the string ABCDEF is","ABCDEF"[3])


The fourth character of the string ABCDEF is D

3.5.2 Numeric Literals

Numeric literals are fixed numerical values. Python has many types of numeric
literals: integer number, floating-point number, and complex number.

[Link] Integer Literals

Integer literals represent whole numbers. In Python, integer literals can be classified
as decimal integer, octal integer, hexadecimal integer, and binary integer. There is no limit
on the number of digits in an integer literal. Further, we can use an underscore (_) to
separate the two adjacent digits of an integer literal for better clarity and readability. The
underscore is ignored when processing an integer literal. For example, 100 can be written
as 1_0_0. However, we cannot use more than one underscores to separate two consecutive
digits. For instance, 1__0_0 will raise the invalid decimal literal error. Also, note that leading
zeros in decimal integer literals are not allowed. For example, the statement a=0100 will
raise an error.

A hexadecimal integer literal begins with 0x, an octal integer literal begins with 0o,
and a binary integer literal begins with 0b. For example, the decimal literal 100 can be

75
represented in hexadecimal, octal, and binary integer literals as 0x64, 0o144, and 0b1100100,
respectively. Irrespective of the types of integer literals used to assign a value to a variable,
print () function will always print the variable's value as a decimal integer only.
To print the integer literal in the hexadecimal, octal, or binary format, we have to convert
an integer literal to an equivalent string using the built-in functions hex (), oct (), and bin (),
respectively. For example, hex (100) will return '0x64', oct (100) will return '0o144', and bin
(100) will return '0b1100100'. The returned string literals can be converted back to integers
with the help of the int () function. A proper base value should be used for the correct
conversion. For example, to convert into an equivalent integer, use int ('0x64', 16).
Similarly, to convert '0o144', use int ('0o144', 8) and for '0b1100100', use int('0b1100100', 2).
The second parameter in the function int () is the base value of the number system of the
first parameter. However, we can use any form of integer literals in calculations directly.
For example, the expression 100+0x64+0o144+0b1100100 is a valid Python expression and
evaluates to 400. Example 3.8 shows the above concepts.

Example 3.8: Various types of integer literals

>>> a=100 #This will store integer literal 100 in variable a


>>> b=0100 #This will generate an error due to the leading zero
SyntaxError: leading zeros in decimal integer literals are not
permitted;
use an 0o prefix for octal integers
>>> b=1_0_0 #Underscores are ignored
>>> print(b)
100
>>> b=1__0_0
SyntaxError: invalid decimal literal
>>>#Print function prints different types of int as decimal int
>>> c=0x64 #Create a hexadecimal integer literal
>>> print(c)
100
>>> d=0o144 #Create an octal integer literal
>>> print(d)
100

76
>>> print(hex(c)) #Print a hexadecimal equivalent string
0x64
>>> print(oct(c)) #Print an octal equivalent string
0o144
>>> e=0b1100100 #Create a binary integer
>>> print(e)
100
>>> print(bin(e)) #Print a binary equivalent string
0b1100100
>>> print(int('0x64' ,16))#Convert a hexadecimal integer string into int
100
>>> print(int('0o144' ,8))#Convert an octal integer string into int
100
>>> print(int('0b1100100',2)) #Convert a binary integer string into int
100
>>> print(a+c+d+e)
400
>>> f=100+0x64+0o144+0b1100100 #Addition of different types of literals
>>> print(f)
400
>>>

[Link] Floating-point Literals

Any number with a fraction (fraction value may be zero) and a decimal point is a
floating-point literal, for example, 100.50, 31.4, 0.0012, -10.25. A floating-point literal can
4e1,
1.2e-3, -1.025e1. Like integer literals, an underscore can also separate consecutive digits of a
float literal for enhanced readability. For example, 1.23_4e1_2 is a valid float number.
Python float literals are 64-bit double-precision values. The maximum value of a float literal
is approximately 1.8 x 10308. Example 3.9 shows the above concepts.

77
Example 3.9: Floating-point literals

>>> a=3.14
>>> b=3.12e2
>>> print(a,b)
3.14 312.0
>>> a=1.23_4e1_2 #underscores are ignored
>>> print(a)
1234000000000.0
>>> c=1.0e-2
>>> print(c)
0.01
>>> import sys #import sys module
>>> sys.float_info #shows the information of float literals.
Sys.float_info(max=1.7976931348623157e+308, max_exp=1024,
max_10_exp=308,
min=2.2250738585072014e-308, min_exp=-1021,
min_10_exp=-307, dig=15, mant_dig=53,
epsilon=2.220446049250313e-16, radix=2, rounds=1)

[Link] Complex Number Literals

Mathematically, a complex number has two parts: real and imaginary. It is


expressed in the form a + bi, where a and b are real numbers, and i represents the imaginary
unit, satisfying the equation i2 . Because no real number satisfies this equation, i is called
an imaginary number. Python creates a complex number by adding a floating literal with
an imaginary literal. An imaginary literal is created by suffixing the letter j to a floating
literal, for example, 2.5j. Some examples of complex numbers in Python are 10+5j, 2.5-3.5j,
1.2e2-1.3e3j. We can also write the imaginary part before the real part of a complex number.
For example, 5j+4 is a valid complex literal.

A complex number can also be created using the complex () function, which takes
either two real numbers or a string as its parameters. For example, to create the complex

78
number 10+20i, we can use the expressions complex(10,20) or . We can
obtain the real and imaginary parts of a complex number using real and imag attributes of
the number, respectively. For example, [Link] will return the real part of a complex number
c, and [Link] will return the imaginary part. The abs () function returns the absolute value
of a complex number. Example 3.10 illustrates the above concepts.

Example 3.10: Complex numbers

>>> a=3.5j #Create an imaginary literal


>>> type(a)
<class 'complex'>
>>> b=2.5+3.6j #Create a complex number
>>> type(b)
<class 'complex'>
>>> c=complex(3,4) #Create a complex number
>>> d=complex('4-5j') #Create a complex number
>>> print(a,b,c,d)
3.5j (2.5+3.6j) (3+4j) (4-5j)
>>> [Link] #get the real part of a complex number
3.0
>>> [Link] #get the imaginary part of a complex number
4.0
>>> abs(c) #get the absolute value of a complex number
5.0

3.5.3 Boolean Literals

There are only two Boolean literals in Python: True and False. True represents true
logical value, and False represents false logical value. Boolean literals is of the bool type.
Hence, type(True) will return 'bool'. In python, the numerical value of True is 1 and of
False is 0, when used in arithmetic expressions. For example, the expression 2+False is equal
to 2, and the expression 2+True is equal to 3. A relational expression, such as a>b, will return
True if it satisfies the given condition; else, it will return False. For example, 10<20 will

79
evaluate to True, whereas 10>20 will evaluate to False. Example 3.11 illustrates the above
concepts.

Example 3.11: Boolean literals

>>> a=True #Create a Boolean variable from a Boolean literal


>>> type(a) #Get the type of an object
<class 'bool'>
>>> type(True)
<class 'bool'>
>>> b=False
>>> print(a,b)
True False
>>> c=10>20 #Create a Boolean variable from a relational expression
>>> d=10<20
>>> print(c,d)
False True
>>> e=2+True #Using a Boolean literal in an arithematic expression
>>> f=2+False
>>> print(e,f)
3 2

3.5.4 Collection Literals

Python has four different types of collection literals: List, Tuple, Dict, and Set. They
are briefly discussed in the following sections but are discussed in greater detail in later
chapters, as they are vital in Python programming.

[Link] List Literals

A list literal is a collection of literals of different data types. The values stored in a
list literal are separated by comma (,) and enclosed within square brackets ([]). For example,
a=[1,2,3, 'Four', 'Five']. We can access an individual item in a list using an index. For
example, a[2] will return 3. A list literal can contain other list literals or any other collection

80
literals. The variable created by assigning a list literal is mutable, i.e., we can modify the
contents of a list variable. Example 3.12 illustrates the above concepts.

Example 3.12: List literals

>>> a=[1,2,3,'four','five']#Create a list variable from a list literal


>>> type(a) #Get the type of a variable
<class 'list'>
>>> a[2] #Access an item of a list
3
>>> a[4]
'five'
>>> b=[1,2,3,[4,5,6],'Seven'] #A list containing another list
>>> b[3]
[4, 5, 6]
>>> [Link]('six') #Add an item to a list
>>> a
[1, 2, 3, 'four', 'five', 'six']
>>> a[2]
3
>>> a[2]=4 #Modify an element of a list
>>> a
[1, 2, 4, 'four', 'five', 'six']

[Link] Tuple Literals

Similar to a list literal, a tuple literal is also a collection of literals of different data
types, but it is immutable. It means that once a tuple is assigned to a variable, the content
of the variable cannot be modified. However, we can assign a new tuple to the variable. A
tuple literal is enclosed in parenthesis, (), and each element is separated by a comma (,). For
example, a = (1,2,3, 'Four', 'Five'). Like a list, we can access an individual item of a tuple
using indexing. For example, a[2] will return 3. An attempt to modify a will result in an
error. Example 3.13 illustrates the above concepts.

81
Example 3.13: Tuple literals

>>> a=(1,2,3,'Four','Five')#Create a tuple variable using a tuple


>>> a
(1, 2, 3, 'Four', 'Five')
>>> a[2] #Accessing an item of a tuple
3
>>> a[2]=4 #Error: Cannot modify the content of a tuple
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
a[2]=4
TypeError: 'tuple' object does not support item assignment

[Link] Dictionary Literals

A dict literal (dict stand for dictionary) uses a pair of curly brackets to store a
collection of data in the form of key: value pairs. A key and its value are separated by a
colon (:). It uses curly-braces '{}' to enclose key: value pairs and the consecutive pair is
separated by a comma (,). The key values are distinct and unique in a dict literal. If we repeat
a key in a dict literal, the last key: value pair will overwrite the previous one.

We can use only an immutable object/literal, such as a string, tuple, integer, as a


key. However, the value of a key can be any mutable or immutable object/literal. For
example, we cannot use a list object/literal as a key, but we can use it as a value. The keys
in a dict object can be of different types of data. The same is also valid for values. The dict
is a mutable data type; hence it cannot be used as a key in a dictionary. Example 3.14
illustrates the above concepts.

Example 3.14: Dict literals

>>> a={1:'One',2:'Two',3:'Three'} #Integers are used as keys.


>>> print(a)
{1: 'One', 2: 'Two', 3: 'Three'}

82

You might also like