Python Sample
Python Sample
Introduction to Python
Rachna Verma
Arvind Kumar Verma
i
Introduction to Python
Rachna Verma
Professor of Master of Computer Application,
Faculty of Engineering and Architecure,
JNV 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]
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
xv
About the Authors
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
1
Input devices Central processing unit Output devices
Memory
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.
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.
Control unit
Registers
Memory
3
1.1.4 Memory
Computer memory
System Software can be of the following types, based on the kind of work they perform:
(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
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.
7
Ease of programming
Python, Java, C++, C,
FORTRAN, JavaScript
High Level Languages
Assembly code
Machine code
Computer hardware
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.
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.
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.
9
compiled languages. Examples of popular interpreted languages are PHP, Ruby, Python,
and JavaScript.
Source code
Specific Compiler
Assembly code
Assembler
Object code
Other object
Libraries Linker codes
Executable code
10
Source code
Executable code
Source code
Generic compiler
Byte code
11
Table 1.2: Comparison of compiled and interpreted languages
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.
12
programming skills. It is strongly recommended that a learner should master to use these
tools.
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.
Algorithms should use the most effective and efficient way out of the different ways
to solve a problem.
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
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
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
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
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
18
Input-Output It represents input or output operations, i.e., reading
(Parallelogram) or writing data from/to input/output devices.
19
Example 1.7: A flowchart to add two numbers entered by the user.
Start
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
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
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.
Output
25
Chapter Summary
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
Programming Exercises
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.
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 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.
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.
Python is one of the easiest programming languages to learn and use due to:
These features also make the Python code readable and easy to maintain and reuse.
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.
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.
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.
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)).
37
Step 4: Click the close button. Python is now installed on your system.
38
2.4 Starting Python in Windows
Once Python is installed, we can use Python in two ways: Python command prompt
and Python IDLE.
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].
39
Figure 2.5: Writing Python program at the command prompt
Program [Link]
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
42
Figure 2.9: Script editor
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.
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.
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.
>>> 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.
>>> a=1\
+2\
+3\
+4
>>> print(a)
10
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.
#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
48
if c <10:
print(a+b) #Properly indented block
print(a*b)
else:
print(a-b)
print(a/b)
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
#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
x=[Link](10,100)
y=[Link](10,100)
z=[Link](10,100)
print("The largest of (",x,",",y,",",z,") is ",largest(x,y,z))
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 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.
Use a consistent naming convention. For example, refer to the naming convention
section 2.8 below, which describes a widely used naming convention.
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.
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.
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.
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]
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
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) %
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
59
60
Chapter 3
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.
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
: 30
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.
Python Token
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()
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".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
Keyword Description
64
as To create an alias
continue To skip the remaining portion of the body of a loop and continue the
next iteration of the loop
65
import To import a module
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.
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
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.
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 bytes
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,
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.
>>> 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
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.
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.
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.
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}"
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
Numeric literals are fixed numerical values. Python has many types of numeric
literals: integer number, floating-point number, and complex number.
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.
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
>>>
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)
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.
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.
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.
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.
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 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.
82