0% found this document useful (0 votes)
9 views36 pages

PythonUnit IModule

The document outlines the syllabus for the Python Programming course for the academic year 2024-25, focusing on the basics of Python, including its features, interpreter, and interactive mode. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various applications. Additionally, it covers tokens, keywords, identifiers, and literals essential for programming in Python.

Uploaded by

anaikutti329
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)
9 views36 pages

PythonUnit IModule

The document outlines the syllabus for the Python Programming course for the academic year 2024-25, focusing on the basics of Python, including its features, interpreter, and interactive mode. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various applications. Additionally, it covers tokens, keywords, identifiers, and literals essential for programming in Python.

Uploaded by

anaikutti329
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Regulation 2023

Academic Year 2024-25

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING


(Common to CSE, CS, IT, ECE, AI&DS & AI&ML)
SUB CODE: 23CS2301 YEAR/SEM: I /II
SUBJECT : PYTHON PROGRAMMING BATCH: 2024-2028
UNIT-I: BASICS
Python interpreter and interactive mode – Tokens- Data types – Numbers and mat functions – Input and
output operations - Comments – Reserved words – Indentation – Operators and Expressions – Precedence
and associativity – Type Conversion – Debugging – Common errors in Python.
Activities: Program to perform exchanges the values of two variables; Circulate the values of n variables,
Distance between two points.

1.1 INTRODUCTION
Python is an exciting and powerful language with the right combination of performance and features
that makes programming fun and easy. It is a high-level, interpreted, interactive, object-oriented, and a
reliable language that is very simple and uses English-like words. It has a vast library of modules to
support integration of complex solutions from pre-built components.
Python is an open-source project, supported by many individuals. It is a platform-independent, scripted
language, with complete access to operating system APIs. Python is a complete programming language
with following features.
1.1.1 Features of Python
 Simple
Python is a simple and a small language. Reading a program written in python feels almost like
reading English. This is in fact the greatest strength of python which allows programmers to
concentrate on the solution to the problem rather than the language itself.
 Easy to Learn
A python program is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords and a clearly defined syntax. This makes it easy for just anyone to
pick up the language quickly.
 Versatile
Python supports development of a wide range of applications ranging from simple text
processing to WWW browsers to games.
 Free and Open Source
Python is an example of open source software. Therefore, anyone can freely distribute it, read
the source code, edit it, and even use the code to write new(free) programs.
 High-level Language
When writing programs in python, the programmers dn‘t have to worry about the low-level
details like managing memory used by the program, etc. They just need to concentrate on writing
solutions of the current problem at hand.
 Interactive
Programs in python work in interactive mode which allows interactive testing and debugging of
pieces of code. Programmers can easily interact with the interpreter directly at the python prompt
to write their programs
 Portable
Python is a portable language and hence the programs behave the same on a wide variety of
hardware platforms and have the same interface on all platforms. The programs work on any of
the operating systems like Linux, windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS,
AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS,
VxWorks, PlayStation, Sharp Zaurus, Windows CE, and even Pocket PC without requiring any
changes.

1
Regulation 2023
Academic Year 2024-25
 Object Oriented
Python supports object-oriented as well as procedure-oriented style of programming. While
object-oriented technique encapsulates data and functionalities within objects, procedure-
oriented technique, on the other hand, builds the program around procedures or functions which
are nothing but reusable pieces of programs. Python is powerful yet simple language for
implementing OOP concepts, especially when compared to languages like C++ or Java.
 Interpreted
Python is an interpreted language; this means that the Python installation interprets and executes
the code a line-at-a-time. An interpreted language has a simpler execute cycle and also works
faster.
Python is processed at run-time by the interpreter. So, there is no need to compile a program
before executing it. We can simply run the program. Basically, python converts the source code
into an intermediate form called bytecode, which is then translated into the native language of
computer so that it can be executed. Byte-code makes the python code portable since users just
have to copy the code and run it without worrying about compiling, linking and loading
processes.
 Dynamic
Python executes dynamically. Programs are written in python can be copied and used for flexible
development of applications. If there is any error, it is reported at run-time to allow interactive
program development.
 Extensible
Python is open source software; anyone can add low-level modules to the python interpreter.
These modules enable programmers to add or customize their tools to work more efficiently.
Moreover, if we want a piece of code not to be accessible for everyone, then we can even code
that part of our program in C or C++ and then use them from our python program
 Embeddable
Programmers can embed python within their C, C++, COM, ActiveX, CORBA, and Java
programs to give ‗scripting‘ capabilities for users.
 Extensive Libraries
Python has a huge library that is easily portable across different platforms. These library
functions are compatible on UNIX, Windows, Macintosh, etc. It allows programmers to perform
a wide range of applications varying from text processing, maintaining databases, to GUI
programming. Besides the above stated features, python has a big list of good features, such as
 Easy Maintenance: code written in python is easy to maintain
 Secure: the python language environment is secure from tampering. Modules can be
distributed to prevent altering the source code. Apart from this, additional security checks
can be easily added to implement additional security features.
 Robust: Python programmers cannot manipulate memory directly. Moreover, errors are
raised as exceptions that can be catch and handled by the program code. For every
syntactical mistake, a simple and easy to interpret message is displayed. All these things
make the language robust.
 Multi-threaded: Python supports multi-threading that are executing more than one
process of a program simultaneously. It also allows programmers to perform process
management tasks.
 Garbage Collection: The python run-time environment handles garbage collection of all
Python objects. For this, a reference counter is maintained to assure that no object that is
currently in use is deleted. An object is no longer used or has gone out of scope are eligible
for garbage collection. This frees the programmers from the worry of memory leak
(failure or delete) and dangling reference (deleting too early) problems. However, the
programmers can still perform memory management functions by explicitly deleting an
unused object.

2
Regulation 2023
Academic Year 2024-25
1.2 PYTHON INTERPRETER AND INTERACTIVE MODE
1.2.1 Python Interpreter
A python interpreter is a computer program that converts each high-level program statement into
machine code. An interpreter translates the command that write out into code that the computer can
understand.
Computer programmers write in high-level programming languages. High-level languages are
written closer to human language and allow programmers to focus on the command being written.
Python is the most famous example of a high-level language. However, while high-level languages
are relatively easy to understand by humans, the same cannot be said for machines. Machines only
understand machine code or machine language, a language represented by strings of bits — 1s and 0s.
When using a Python interpreter, the programmer types in the command, the interpreter reads the
command, evaluates it, prints the results, and then goes back to read the command.
Computer programs are generally written in a high-level language, also called source code. Since
machines don‘t understand this type of language, the language needs to be transformed into binary or
machine code, which machines understand. Compilers and interpreters make this transformation
possible. However, while they both have the primary function of changing source code into machine
code, there are differences between them. These two remarkable tools significantly differ in how they
translate the source code.
 Interpreters translate source code one statement at a time. On the other hand, the compiler first
scans the entire program and then translates the whole program into machine code.
 Interpreters translate programs one statement at a time, unlike compilers that do ―batch
translation.‖ Therefore, interpreters usually take less time to analyze the source code. However,
while they analyze code faster, compilers execute the code faster than interpreters.
 Interpreters don‘t generate any Object code, they are more memory efficient than compilers.
Working of interpreter in python
The Python interpreter is CPython and is written in the C programming language. First,
the interpreter checks or analyzes the source code. CPython receives the source code and
initializes several commands to do some vital things. First, the interpreter ensures that the
program is followed Python‘s syntax for writing code. It also checks for incorrect lines of code.
If it encounters any error in a line, it stops the program from running and produces an error
message. This analysis divides the source code files into a list of tokens. The interpreter then
generates byte code.
After receiving the tokens, the interpreter generates the Abstract Syntax Tree or AST.
This tree is converted to machine language (i.e., 1s and 0s). Because this is a Python interpreter,
the code can be saved in a file with the .pyc extension. Next, the interpreter initializes the
Python Virtual Machine (PVM). PVM is crucial because it‘s what converts the byte code into
binary code. After conversion, the results are then printed. Python prints out the correct result
if there are no high-level language errors. Otherwise, it prints out an error message.
The basic Python interpreter allows us to execute single statements. However, if we
want to execute multiple statements or build Python applications, then we will in need of
Integrated Development Environment (IDE). These applications give programmers extensive
software capabilities like editing source code, building executable, and debugging. Some of the
best IDEs we recommend include:
 Sublime Text 4
 Visual Studio Code
 Atom
 Jupyter
 Spyder

1.2.2 Interactive Mode


Python is a high level programming language that helps a user to run a program and integrate
systems more efficiently; as it executes a program in comparatively fewer lines of code. In this
3
Regulation 2023
Academic Year 2024-25
programming language, a code can be run in two ways
 Interactive Mode: In this mode, we type one command at a time and Python executes the same.
Python‘s interactive interpreter is also called Python Shell.
 Script Mode: In this mode, we save all our commands in the form of a program file and later
run the entire script. After running the script, the whole program gets compiled and sees the
overall output.
Among interactive mode and script mode in Python, Interactive Mode in Python provides a dynamic
environment for developers to interactively write and execute Python statements line by line. It offers
a way to experiment, test code snippets, and receive immediate feedback for each command entered.
Unlike Script Mode, which involves creating separate script files, Interactive Mode allows developers
to input code directly and observe the results in real-time.
Using Interactive Mode
1. Accessing Interactive Mode:
Interactive Mode is typically accessed by opening a terminal or command prompt and entering
the python command without specifying a script filename. This opens the Python interpreter in
interactive mode, indicated by the >>> prompt.
2. Entering Statements:
Developers can now enter Python statements directly at the prompt. Each statement is executed
immediately after pressing "Enter," and the result (if any) is displayed instantly.
3. Immediate Feedback:
The Python interpreter responds to each statement by displaying the output, such as variable values,
calculations, or printed text.

1.3 TOKENS
The smallest unit/element in the python program/script is known as a Token or a Lexical unit.
Python has following Tokens:
 Keywords
 Identifiers
 Literals
 Operators
 Punctuators
 Keywords
Keywords are the reserve words/pre-defined words/special words of python which have
a special meaning for the interpreter. They can‘t be used as variable names, function names, or
any other random purpose. They are used for their special features. In Python we have 33
keywords some of them are: try, False, True, class, break, continue, and, as, assert, while, for, in,
raise, except, or, not, if, elif, print, import, etc.
 Identifiers(user defined names)
Identifiers are the name given to the different programming elements like variables,
objects, classes, functions, lists, dictionaries etc. Python is a case-sensitive language and it has
some rules and regulations to name an identifier. Here are some rules to name an identifier:-
 Python is case-sensitive. So case matters in naming identifiers. And hence names and
Names are two different identifiers.
 Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It
can‘t start with any other character.
 Except for letters and underscore, digits can also be a part of identifier but can‘t be the
first character of it.
 Any other special characters or whitespaces are strictly prohibited in an identifier.
 An identifier can‘t be a keyword.
 Literals
Literals are the data items that have a fixed or constant value. Literals are essential building
elements of Python programming, expressing fixed values directly inserted within code. They
4
Regulation 2023
Academic Year 2024-25
include many data kinds, each serving a specific role in relaying information to the interpreter.
Various types of literal are supported by Python, including:
 String Literals: The text written in single, double, or triple quotes represents the string
literals in Python. For example: ―Computer Science‖, ‗sam‘, etc. We can also use triple
quotes to write multi-line strings. A string literal is a sequence of characters surrounded
by Quotes.
Example:
string = 'Hello'
s = "World"
A = "'Python is a
high-level and
general purpose language'"

 Character Literals: Character literal is also a string literal type in which the character
is enclosed in single or double-quotes.
Example:
a = 'G'
b = "W"
 Numeric Literals: These are the literals written in form of numbers. Python supports
the following numerical literals:
o Integer Literal: It includes both positive and negative numbers along with 0. It
doesn‘t include fractional parts. It can also include binary, decimal, octal,
hexadecimal literal.
o Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
o Complex Literal: It includes a+bi numeral, here a represents the real part and b
represents the complex part.
 Boolean Literals: Boolean literals have only two values in Python. These are True and
False.
 Special Literals: Python has a special literal ‗None‘. It is used to denote nothing, no
values, or the absence of value.
Example:
var = None
print(var)
 Literals Collections
List, dictionary, tuple, and sets are examples of Python literal collections.
o List: It is a comma-separated list of components enclosed in square brackets.
These elements can be of any data type and can be changed.
o Tuple: In round brackets, this is similar to a list having comma-separated items
or values. The values are fixed and can have any Python data type.
o Dictionary: This data structure is an unordered set of key-value combinations.
o Set: It is the group of components enclosed in curly braces, "{}"
Example:
# A list literal collection
my_list = [23, "Python", 1.2, 'Character']

# A tuple literal collection


my_tuple = (1, 3, 6, 'world')

# A dictionary literal collection


my_dict = {'a': 1, 'b': 2, 'c': 3}

5
Regulation 2023
Academic Year 2024-25
# A set literal collection
my_set = {5, 3, 7, 9}
 Operators
Operators are the symbols or a word that perform some kind of operation on given values
(operands) in an expression and returns the result. These are the tokens responsible to perform
an operation in an expression. The variables on which operation is applied are called operands.
Operators can be unary or binary. Unary operators are the ones acting on a single operand like
complement operator, etc. While binary operators need two operands to operate.
Example:
# Operators
a = 12

# Unary operator
b=~a

# Binary operator
c = a+b
 Punctuators
Punctuators are the symbols that are used in programming language to organize sentence
structure, indicate the rhythm and emphasis of expressions, statements and program structure.
Common Punctuators are
‗ ‗‘ ―‖ # \ ( ) { } [ ] @ , : . ;

1.4 DATA TYPES


Data types are the classification or categorization of data items. Data types are used to identify the
type of data and set of valid operations which can be performed on it.
Python Data Types

Since everything is an object in Python programming, data types are actually classes and variables are
instances(object) of these classes.
1.4.1 Numeric Data Types
The numeric data type in Python represents the data that has a numeric value. A numeric value can
be an integer, a floating number, or even a complex number. These values are defined as Python
int, Python float, and Python complex classes in Python.
 Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
6
Regulation 2023
Academic Year 2024-25
 Complex Numbers – A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Example:
a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
1.4.2 Sequence Data Type
The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence types in Python –
 String
 List
 Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote, or triple-quote. In Python
there is no character data type, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes, or even triple quotes. In
Python programming, individual characters of a String can be accessed by using the method of
Indexing. Negative Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
Example:
String1 = 'Welcome to World'
print("String with the use of Single Quotes: ")
print(String1)
String1 = "It is a python"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
String1 = '''I'm a python and I live in a world of "ML"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
String1 = '''Python
For
programming'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to World
7
Regulation 2023
Academic Year 2024-25
String with the use of Double Quotes:
It is a python
<class 'str'>
String with the use of Triple Quotes:
I'm a python and I live in a world of "ML"
<class 'str'>
Creating a multiline String:
Python
For
Programming
List Data Type
Lists are just like arrays, declared in other language which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type. Lists in Python
can be created by just placing the sequence inside the square brackets[]. In order to access the
list items refer to the index number. Use the index operator [ ] to access an item in a list. In
Python, negative sequence indexes represent positions from the end of the array.
Example:
List = []
print("Initial blank List: ")
print(List)
List = ['Welcome']
print("\nList with the use of String: ")
print(List)
List = ["Welcome", "To", "India"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['Welcome', 'To'], ['India']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List with the use of String:
['Welcome']
List containing multiple values:
Welcome
India
Multi-Dimensional List:
[['Welcome', 'To'], ['India']]
Tuple Data Type
A tuple is also an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class. In Python, tuples are created by placing a sequence of values
separated by a ‗comma‘ with or without the use of parentheses for grouping the data sequence.
Tuples can contain any number of elements and of any datatype. In order to access the tuple items
refer to the index number. Use the index operator [ ] to access an item in a tuple. The index must
be an integer. Nested tuples are accessed using nested indexing.
Example:
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
8
Regulation 2023
Academic Year 2024-25
Tuple1 = ('Welcome', 'India')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('India')
print("\nTuple with the use of function: ")
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'welcome')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Welcome', 'India')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('I', 'n', 'd', 'i', 'a')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'welcome'))

1.4.3 Boolean Data Type


Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‗T‘ and ‗F‘ are valid booleans otherwise python will throw an error.
Example:
print(type(True))
print(type(False))

print(type(true))

Output:
<class 'bool'>
<class 'bool'>

Traceback (most recent call last):


File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined

1.4.4 Set Data Type


In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements. Sets can
be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a ‗comma‘. The type of elements in a set need not be the
9
Regulation 2023
Academic Year 2024-25
same, various mixed-up data type values can also be passed to the set. Set items cannot be accessed by
referring to an index, since sets are unordered the items have no index. But we can loop through the set
items using a for loop, or ask if a specified value is present in a set, by using the in the keyword.
Example:
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("Welcome")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["India", "For", "India"])
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, 'India', 4, 'For', 6, 'India'])
print("\nSet with the use of Mixed Values")
print(set1)
Output:

Initial blank Set:


set()
Set with the use of String:
{'W', 'e', 'l', 'c', 'o', 'm'}
Set with the use of List:
{'India', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'India', 'For'}
1.4.5 Dictionary Data Type
A dictionary in Python is an unordered collection of data values, used to store data values like a map,
unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair.
Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary
is separated by a colon : , whereas each key is separated by a ‗comma‘. In Python, a Dictionary can be
created by placing a sequence of elements within curly {} braces, separated by
‗comma‘. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can‘t be
repeated and must be immutable. The dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing it in curly braces{}. In order to access the items of a
dictionary refer to its key name. Key can be used inside square brackets. There is also a method called
get() that will also help in accessing the element from a dictionary.
Example:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'India', 2: 'For', 3: 'India'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'India', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'India', 2: 'For', 3: 'India'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'India'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
10
Regulation 2023
Academic Year 2024-25
print(Dict)
Output:

Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'India', 2: 'For', 3: 'India'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'India'}
Dictionary with the use of dict():
{1: 'India', 2: 'For', 3: 'India'}
Dictionary with each item as a pair:
{1: 'India', 2: 'For'}

1.5 NUMBERS AND MATH FUNCTIONS


Python has a set of built-in math functions, including an extensive math module. It allows to
perform mathematical tasks on numbers.
Built-in Math Functions
 The min() and max() functions can be used to find the lowest or highest value in an iterable.
Example:
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)//5
print(y)//25
 The abs() function returns the absolute (positive) value of the specified number
Example
x = abs(-7.25)
print(x) //7.25
 The pow(x, y) function returns the value of x to the power of y (xy).
Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)//64
 The math.sqrt() method returns the square root of a number
Example
import math
x = math.sqrt(64)
print(x)//8
 The math.ceil() method rounds a number upwards to its nearest integer, and the
math.floor() method rounds a number downwards to its nearest integer, and returns the result
Example
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
 The math.pi constant, returns the value of PI (3.14...)
import math
x = math.pi

print(x)
 The math.cos() method returns the cosine of a number.
11
Regulation 2023
Academic Year 2024-25
math.cos(x)
where x-is a number to find the cosine of. If the value is not a number, it returns a
TypeError
 The math.dist() method returns the Euclidean distance between two points (p and q), where
p and q are the coordinates of that point.
math.dist(p, q)
The two points (p and q) must be of the same dimensions.
 The math.exp() method returns E raised to the power of x (Ex).
'E' is the base of the natural system of logarithms (approximately 2.718282) and x is the
number passed to it.
math.exp(x)
 The math.factorial() method returns the factorial of a number.
This method only accepts positive integers.
The factorial of a number is the sum of the multiplication, of all the whole numbers, from
our specified number down to 1. For example, the factorial of 6 would be 6 x 5 x 4 x 3 x 2
x 1 = 720
math.factorial(x)
 The math.fmod() method returns the remainder (modulo) of x/y.
math.fmod(x, y)
 If both x and y = 0, it returns a ValueError.
 If y = 0, it returns a ValueError.
 If x or y is not a number, it returns a TypeError.
 The math.fsum() method returns the sum of all items in any iterable (tuples, arrays, lists,
etc.).
math.fsum(iterable)
where iterable is the list, tuple, array to sum. If the iterable is not numbers, it returns a
TypeError
 The math.gcd() method returns the greatest common divisor of the two integers int1 and
int2.
GCD is the largest common divisor that divides the numbers without a remainder. GCD is
also known as the highest common factor (HCF).
math.gcd(int1, int2)
 The math.isnan() method checks whether a value is NaN (Not a Number), or not.
This method returns True if the specified value is a NaN, otherwise it returns False.
math.isnan(x)
 The math.prod() method returns the product of the elements from the given iterable.
math.prod(iterable, start)
iterable It is required, Specifies the elements of the iterable whose product is computed
by the function
start it is an optional, Specifies the starting value of the product. Default value is 1
 The math.remainder() method returns the remainder of x with respect to y.
math.remainder(x, y)
 The math.trunc() method returns the truncated integer part of a number.
This method will NOT round the number up/down to the nearest integer, but simply remove
the decimals.
math.trunc(x)

1.6 INPUT AND OUTPUT OPERATIONS


In Python, program output is displayed using the print() function, while user input is obtained with
the input() function. Python treats all input as strings by default, requiring explicit conversion for
other data types.

12
Regulation 2023
Academic Year 2024-25
Python Input
Sometimes, users or developers want to run the programs with their own data in the variables for
their own ease. To execute this, we will learn to take input from the users, in which the users
themselves will define the values of the variables. The input() statement allows us to do such things
in Python.

The syntax for this function is as follows:


input('prompt ')
Here, prompt is the string we want to display while taking input from the user. This is optional.
 Python get user input with a message
# Taking input from the user
name = input("Enter your name: ")

# Output
print("Hello, " + name)
print(type(name))
Output:

Enter your name: Jeeva


Hello, Jeeva
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other data type
we have to convert the input explicitly. For example, to convert the input to int or float we have
to use the int() and float() method respectively.
 Integer input in Python
# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1
# Output
print(add)
Output:
Enter a number: 25
26
 Multiple Inputs in Python :
we can take multiple inputs of the same data type at a time in python, using map() method
in python.
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)
Output :
Enter the Numbers : 2 3 4
The Numbers are : 2 3 4
 Inputs for the Sequence Data Types like List, Set & Tuple
In the case of List and Set the input can be taken from the user in two ways.
1. Taking List/Set elements one by one by using the append()/add() methods.
2. Using map() and list() / set() methods.
1. Taking List/Set elements one by one
The elements of the List/Set is read one by one by using the append() method in the case of
List, and add() method in the case of a Set.

Example:
List = list()
13
Regulation 2023
Academic Year 2024-25
Set = set()
l = int(input("Enter the size of the List : "))
s = int(input("Enter the size of the Set : "))
print("Enter the List elements : ")
for i in range(0, l):
List.append(int(input()))
print("Enter the Set elements : ")
for i in range(0, s):
Set.add(int(input()))
print(List)
print(Set)
Output :
Enter the size of the List : 4
Enter the size of the Set : 3
Enter the List elements :
9
0
1
3
Enter the Set elements :
2
9
1
[9, 0, 1, 3]
{9, 2, 1}
2. Using map() and list() / set() Methods

List = list(map(int, input("Enter List elements : ").split()))


Set = set(map(int, input("Enter the Set elements :").split()))
print(List)
print(Set)
Output :
Enter List elements : 3 4 8 9 0 11
Enter the Set elements :34 88 230 234 123
[3, 4, 8, 9, 0, 11]
{34, 230, 234, 88, 123}
3. Taking Input for Tuple
We know that tuples are immutable, there are no methods available to add elements to tuples.
To add a new element to a tuple, first type cast the tuple to the list, later appends the element
to the list, and again type cast list back to a tuple.

Example:
T = (2, 3, 4, 5, 6)
print("Tuple before adding new element")
print(T)
L = list(T)
L.append(int(input("Enter the new element : ")))
T = tuple(L)
print("Tuple After adding the new element")
print(T)
Output :
Tuple before adding new element
14
Regulation 2023
Academic Year 2024-25
(2, 3, 4, 5, 6)
Enter the new element : 35
Tuple After adding the new element
(2, 3, 4, 5, 6, 35)
Python Output
Python provides the print() function to display output to the standard output devices.
Syntax: print(value(s), sep= ‗ ‗, end = ‗\n‘, file=file, flush=flush)

Parameters:
o value(s) : Any value, and as many as . Will be converted to string before printed
o sep=‘separator‘ (Optional) : Specify how to separate the objects, if there is more than
one.Default :‘ ‗
o end=‘end‘(Optional) : Specify what to print at the end.Default : ‗\n‘
o file (Optional) : An object with a write method. Default :sys.stdout
o flush (Optional) : A Boolean, specifying if the output is flushed (True) or buffered
(False). Default: False
o Returns: It returns output to the screen.
Example 1:
# print() method
print("GFG")

# code for disabling the softspace feature


print('G', 'F', 'G')
Output
GFG
GFG
In the above example, we can see that in the case of the 2nd print statement there is a space
between every letter and the print statement always add a new line character at the end of the
string. This is because after every character the sep parameter is printed and at the end of the
string the end parameter is printed.
Example 2 : Python Print output with custom sep and end parameter
print("GFG", end = "@")
# code for disabling the softspace feature
print('G', 'F', 'G', sep="#")
Output
GFG@G#F#G

Formatting Output
Formatting output in Python can be done in many ways.
 Using formatted string literals
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.

Example: Python String formatting using F string

# Declaring a variable
name = "Gfg"

# Output
print(f'Hello {name}! How are you?')
Output:
15
Regulation 2023
Academic Year 2024-25

Hello Gfg! How are you?

 Using format()
We can also use format() function to format our output to make it look presentable. The curly
braces { } work as placeholders. We can specify the order in which variables occur in the output.

Example: Python string formatting using format() function

# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
# Output
print('The value of a is {} and b is {}'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,
value_b = b,
sub_value = sub))
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10

 Using % Operator
We can use ‗%‘ operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‗printf‘ in the C programming language.

%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
Example:

# Taking input from the user


num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)
Output:

Enter a value: 50
The sum is 55

1.7 COMMENTS
Comments are the non-executable statements in a program. It is just added to describe the statements
16
Regulation 2023
Academic Year 2024-25
in the program code. Comments make the program easily readable and understandable by the
programmer as well as other users who are seeing the code. The interpreter simply ignores the
comments. Comments can be used to explain Python code. Comments can be used to make the code
more readable.
Types of Comments in Python
In Python, there are two types of comments:
 single-line comment
 multi-line comment
Single-line comments
A single-line comment starts and ends in the same line. We use the # symbol to write a
single-line comment.
Example:
# create a variable
name = 'Eric Cartman'

# print the value


print(name)
Output
Eric Cartman
Here, we have created two single-line comments:
# create a variable
# print the value
We can also use the single-line comment along with the code.
name = 'Eric Cartman' # name is a string
Here, code before # are executed and code after # are ignored by the interpreter.
Multi-line comments
Python doesn't offer a separate way to write multiline comments. However, there is other
ways to get around this issue.

We can use # at the beginning of each line of comment on multiple lines.


For example,
# This is a long comment
# and it extends
# to multiple lines
Here, each line is treated as a single comment, and all of them are ignored.

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But if we do not assign it to any
variable or function, we can use it as a comment.The interpreter ignores the string that is not
assigned to any variable or function.

Let's see an example,


''' This is also a
perfect example of
multi-line comments '''
Here, the multiline string isn't assigned to any variable, so it is ignored by the interpreter. Even
though it is not technically a multiline comment, it can be used as one.

Advantages of Comments in Python


Comments are generally used for the following purposes:
 Code Readability
17
Regulation 2023
Academic Year 2024-25
 Explanation of the code or Metadata of the project
 Prevent execution of code
 To include resources
Right Way to Write Comments
Comments serve the main purpose to explain our code. Developers use healthy comment writing
practice for better understanding of the code.
 Comments should be short and precise.
 Use comments only when necessary, don‘t clutter our code with comments.
 Comment should have some meaning.
 Avoid writing generic or basic comments.
 Write comments that are self-explanatory.
1.8 RESERVED WORDS
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
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
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator

18
Regulation 2023
Academic Year 2024-25
1.9 INDENTATION
Indentation in Python refers to the whitespaces at the start of the line to indicate a block of code.
We can create an indentation using space or tabs. When writing Python code, we have to define a
group of statements for functions and loops. This is done by properly indenting the statements for
that block.
The leading whitespaces (space and tabs) at the start of a line are used to determine the
indentation level of the line. We have to increase the indent level to group the statements for that
code block. Similarly, reduce the indentation to close the grouping. The four whitespaces or a single
tab character at the beginning of a code line are used to create or increase the indentation
level.

Python Indentation Rules


Below are the rules that one should follow while using indentation:
 The first line of Python code can‘t have an indentation, it will throw IndentationError.
 We should avoid mixing tabs and whitespaces to create an indentation. It‘s because text
editors in Non-Unix systems behave differently and mixing them can cause the wrong
indentation.
 It is preferred to use whitespace than the tab character.
 The best practice is to use 4 whitespaces for the first indentation and then keep adding
additional 4 whitespaces to increase the indentation.
Benefits of Indentation in Python
The proper use of indentation in a program provides many benefits, some of them are:
 Indentation is important to increase the readability of the code by clearly indicating the
hierarchy (i.e. if statements belong to the same block or not).
 This avoids the need to use delimiters such as braces or brackets, which is mandatory in
most programming languages like C, C++, Java, etc.
 Python indentation is consistent throughout the program, making it easier to debug.
 In most programming languages, indentation makes the structure of the code proper.
Python uses it for grouping, making the code automatically beautiful.
 Python indentation rules are very simple. Most of the Python IDEs automatically indent
the code for us, so it‘s very easy to write the properly indented code.
Disadvantages of Indentation in Python
There are only a few disadvantages of indentation in code, let‘s look at them:
 Since whitespaces are used for indentation, if the code is large and indentation is corrupted
then it‘s really tedious to fix it. It happens mostly by copying the code from online sources,
Word documents, or PDF files.
 Most of the popular programming languages use braces for indentation, so anybody coming
from a different programming world finds it hard at first to adjust to the idea of using
whitespaces for indentation
1.10 OPERATORS AND EXPRESSIONS
Operators are the constructs that are used to manipulate the value of operands. Operators are
special symbols that perform operations on variables and values. Operators serve as the foundation
upon which logic is constructed in a program in a particular programming language. In every
19
Regulation 2023
Academic Year 2024-25
programming language, some operators perform several tasks.
Types:
 Arithmetic Operators
 Comparison Operators
 Assignment Operators
 Unary Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
1.10.1 Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. Arithmetic operators
are used with numeric values to perform common mathematical operations. There are many arithmetic
operators.
Operator Operation Sample Result
Expression
+ Addition a+b The arithmetic sum of a and b
- Subtraction a–b b subtracted from a
* Multiplication a*b The product of a and b
/ Division a/b The quotient of a divided by b, expressed as a
float
% Modulo a%b The remainder of a divided by b
// Floor division or a // b The quotient of a divided by b, rounded to the
integer division next smallest whole number
** Exponentiation a**b a raised to the power of b

1.10.2 Comparison Operators


The comparison operators are all binary. This means that they require left and right operands.
These operators always return a Boolean value (True or False) that depends on the truth value of the
comparison at hand. It is also known as relational operators.
Operator Operation Sample Result
Expression
 Return True if the value of a is equal to the value of b
== Equal to a == b
 otherwise False
 Return True if a isn‘t equal to b
!= Not equal to a != b
 otherwise False
 Return True if a is less than b
< Less than a<b
 otherwise False
 Return True if a is less than or equal to b
<= Less than or equal to a <= b
 otherwise False
 Return True if a is greater than b
> Greater than a>b
 otherwise False
Greater than or equal  Return True if a is greater than or equal to b
>= a >= b
to  otherwise False

1.10.3 Assignment Operators


The assignment operator as the name suggests assigns value to the operand. The assignment
operator is one of the most frequently used operators in Python. The operator consists of a single equal
sign (=), and it operates on two operands. The left-hand operand is typically a variable, while the right-
20
Regulation 2023
Academic Year 2024-25
hand operand is an expression or value. The in-place operators is also known as shortcut operators that
includes +=, -=, *=,/=,%=,//= and **=.

Operator Description Syntax


= Assign the value of the right side of the expression to the x= y+z
left side operand
+= Add AND: Add right-side operand with left-side operand a+=b a=a+b
and then assign to left operand
-= Subtract AND: Subtract right operand from left operand a-=b a=a-b
and then assign to left operand
*= Multiply AND: Multiply right operand with left operand a*=b a=a*b

21
Regulation 2023
Academic Year 2024-25
and then assign to left operand
/= Divide AND: Divide left operand with right operand and a/=b a=a/b
then assign to left operand
%= Modulus AND: Takes modulus using left and right a%=b a=a%b
operands and assign the result to left operand
//= Divide(floor) AND: Divide left operand with right a//=b a=a//b
operand and then assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value a**=b a=a**b
using operands and assign value to left operand
&= Performs Bitwise AND on operands and assign value to a&=b a=a&b
left operand
|= Performs Bitwise OR on operands and assign value to left a|=b a=a|b
operand
^= Performs Bitwise XOR on operands and assign value to a^=b a=a^b
left operand
>>= Performs Bitwise right shift on operands and assign value a>>=b a=a>>b
to left operand
<<= Performs Bitwise left shift on operands and assign value a <<= b a= a << b
to left operand

1.10.4 Unary operator


Unary operators are those operators that require a single operand for computations. Python
supports unary minus operator. The operator ‗-‘ is called the Unary minus operator. It is used to negate
the number. The minus operator is used to represent a negative value.
Example:
b=10
a=-(b)
The result of this expression is a=-10, because variable b has a positive value. After applying unary
minus operator (-) on the operand b, the value becomes -10, which indicates it as a negative value

1.10.5 Logical Operators


Logical operators are used to compose Boolean expressions and evaluate their truth values.
They are required for the creation of conditional statements as well as for managing the flow of
execution in programs. Python has three basic logical operators: AND, OR, and NOT.

Sample
Operator Operation Description Result
Expression
&& and If both of the operands x and y  Return true if
are true then the both x and y are true
condition becomes true.  False otherwise
|| or If any of the two x or y  Return true if
operands is non-zero either x or y is true
then the condition  False otherwise
becomes true.
! not Used to reverse the not x  Return true if x is False
logical state of its  False if x is True
operand

1.10.6 Bitwise Operators


22
Regulation 2023
Academic Year 2024-25
Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit.
They work with integer binary representations, performing logical operations on each bit location.
Sample
Operator Operation Result
Expression
& Bitwise AND a&b  Each bit position in the result is the logical AND of the
bits in the corresponding position of the operands.
 1 if both bits are 1, otherwise 0.
| Bitwise OR a|b  Each bit position in the result is the logical OR of the
bits in the corresponding position of the operands.
 1 if either bit is 1, otherwise 0.
~ Bitwise NOT ~a  Each bit position in the result is the logical negation of
the bit in the corresponding position of the operand.
 1 if the bit is 0 and 0 if the bit is 1.
^ Bitwise XOR a^b  Each bit position in the result is the logical XOR of the
(exclusive OR) bits in the corresponding position of the operands.
 1 if the bits in the operands are different, 0 if they‘re
equal.
>> Bitwise right shift a >> n  Each bit is shifted right n places.
<< Bitwise left shift a << n  Each bit is shifted left n places.

1.10.7 Membership Operators


Python membership operators are used to determine whether or not a certain value occurs within
a sequence. They make it simple to determine the membership of elements in various data structures
such as lists, tuples, sets, and strings. Python has two primary membership operators: the in and not in
operators.
Operator Sample Expression Result
in value in collection  True if value is present in collection
 False otherwise
not in value not in collection  True if value is not present in collection of values
 False otherwise

1.10.8 Identity Operators


Python identity operators are used to compare two objects' memory addresses rather than their
values. If the two objects refer to the same memory address, they evaluate to True; otherwise, they
evaluate to False. Python includes two identity operators: the is and is not operators.
Operator Sample Result
Expression
is x is y  True if x and y hold a reference to the same in-memory object
 False otherwise
is not x is not y  True if x points to an object different from the object
that y points to
 False otherwise

1.11 PRECEDENCE AND ASSOCIATIVITY


In Python, operators have different levels of precedence, which determine the order in which they
are evaluated. When multiple operators are present in an expression, the ones with higher precedence
are evaluated first. In the case of operators with the same precedence, their associativity comes into play,
determining the order of evaluation.

23
Regulation 2023
Academic Year 2024-25
Sr.No. Operator Description Associativity
1. ** Exponentiation (raise to the power) Right to Left

24
Regulation 2023
Academic Year 2024-25
2. ~+- Complement, unary plus and minus (method Left to Right
names for the last two are +@ and -@)
3. * / % // Multiply, divide, modulo, and floor division Left to Right
4. +- Addition and subtraction Left to Right
5. >> << Right and left bitwise shift Left to Right
6. & Bitwise 'AND' Left to Right
7. ^| Bitwise exclusive `OR' and regular `OR' Left to Right
8. <= < > >= Comparison operators Left to Right
9. <> == != Equality operators Left to Right
10. = %= /= //= -= Assignment operators Right to Left
+= *= **=
11. is is not Identity operators Left to Right
12 in not in Membership operators Left to Right
13. not or and Logical operators Left to Right

1.12 TYPE CONVERSION


Type conversion is the process of converting data of one type to another. There are mainly two
types of type conversion methods in Python:
 Implicit type conversion- Done automatically by the Python interpreter
 Explicit type conversion- Needs to be done manually by the programmer.
Implicit type conversion
In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion. This type of data type conversion takes place during compilation or during
the runtime.
Example:
a=5
b = 5.5
sum = a + b
print (sum)
print (type (sum)) #type() is used to display the datatype of a variable

Output:
10.5
<class ‗float‘>

In the above example, we have taken two variables of integer, and float data types and added them.
Further, we have declared another variable named ‗sum‘ and stored the result of the addition in it.
When we checked the data type of the sum variable, we could see that the data type of the sum variable
had been automatically converted into the float data type by the Python compiler. This is called implicit
type conversion.

The reason that the sum variable was converted into the float data type and not the integer data type is
that if the compiler had converted it into the integer data type, then it would‘ve had to remove the
fractional part, which would have resulted in data loss. So, Python always converts smaller data types
into larger data types to prevent the loss of data.

Explicit type conversion


Explicit type conversion is also known as typecasting. In Explicit Type Conversion, the data
type is manually changed by the user as per their requirement. With explicit type conversion, there is
a risk of data loss since we are forcing an expression to be changed in some specific data type.
The following table contains some of the in-built functions for type conversion, along
25
Regulation 2023
Academic Year 2024-25
with their descriptions
Function Description

int(y [base]) It converts y to an integer, and Base specifies the number base. For
example, if we want to convert the string into decimal numbers then we‘ll
use 10 as the base.

float(y) It converts y to a floating-point number.

complex(real[imag]) It creates a complex number.

str(y) It converts y to a string.

tuple(y) It converts y to a tuple.

list(y) It converts y to a list.

set(y) It converts y to a set.

dict(y) It creates a dictionary and y should be a sequence of (key, value) tuples.

ord(y) It converts a character into an integer.

hex(y) It converts an integer to a hexadecimal string.

oct(y) It converts an integer to an octal string

The syntax for explicit type conversion:


(required_data type)(expression)
Example 1: Converting integer to float
# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0

Example 2: Python Type conversion using ord(), hex(), oct()


# initializing integer
s = '4'

26
Regulation 2023
Academic Year 2024-25
# printing character converting to integer
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)

# printing integer converting to hexadecimal string


c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)

# printing integer converting to octal string


c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)

Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

Example 3: Python Type conversion using tuple(), set(), list()

# initializing string
s = 'INDIA'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)

Output:
After converting string to tuple : ('I', 'N', 'D', 'I', 'A')
After converting string to set : {'N', 'D', 'A', 'I'}
After converting string to list : ['I', 'N', 'D', 'I', 'A']

1.13 DEBUGGING
In software development, debugging is the process of looking for and then resolving issues that
prevent the software from running correctly.
The Python debugger provides a debugging environment for Python programs. It supports
setting conditional breakpoints, stepping through the source code one line at a time, stack inspection,
and more.
Debugging is a method that involves testing of a code during its execution and code correction.
27
Regulation 2023
Academic Year 2024-25
During debugging, a program is executed several times with different inputs to ensure that it performs
its intended task correctly. While other forms of testing aims to demonstrate
correctness of the programs, testing during debugging, on the other hand is primarily aimed at locating
errors.
Preconditions for Effective debugging
In order to avoid excessive time spent on debugging, the programmer should be mentally prepared
for the effort. The following steps are useful to prepare for debugging.
1. Understand the design and algorithm - If we are working on a module and we do not
understand its design or its algorithms, then debugging will be very difficult. If we don't
understand the design then we can't test the module because we do not know what it is supposed
to do. If we don't understand the algorithms then we will find it very difficult to locate the errors
that are revealed by testing. A second reason for the importance of understanding algorithms is
that we may need that understanding in order to construct good test cases. This is especially
true for algorithms for complex data structures.
2. Check correctness - There are several methods for checking correctness of an implementation
prior to execution. Before debugging, make sure that the code is correct. One useful code check
is to examine code using the logical methods of correctness proofs. For example to check the
correctness of loop statements, we know preconditions, invariants, terminating conditions and
post-conditions. Even if these checks don't find all errors, we will often gain a better
understanding of the algorithm by making the checks.
3. Code tracing - Often, errors can be detected by tracing through the execution of various calls
to module services, starting with a variety of initial conditions for the module. In order to be
effective, tracing of a procedure or function should be done assuming that calls to other
procedures and functions work correctly, even if they are recursive calls. Again, tracing may
not catch all errors, but it can enhance our understanding of algorithms.
4. Peer reviews - A peer review involves having a peer examine our code for errors. To be
effective, the peer should either already be familiar with the algorithm, or should be given the
algorithm and code in advance. When the reviewer meets with the code writer, the code writer
should present the code with explanations of how it correctly implements the algorithm. If the
reviewer doesn't understand or disagrees with part of the implementation, they discuss that part
until both are in agreement about whether or not it is an error. The reviewer's role is only as an
aid to detecting errors. It is left to the developer to correct them. Often the code writer discovers
their own errors during the review. In any case, it is useful to have an outsider review our work
in order to get a different perspective and to discover blind spots that seem to be inherent in
evaluating our own work.
Principles of Debugging
 Report error conditions immediately - Much debugging time is spent zeroing in on the cause
of errors. The earlier an error is detected, the easier it is to find the cause. If an incorrect module
state is detected as soon as it arises then the cause can often be determined with minimal effort.
If it is not detected until the symptoms appear in the client interface then may be difficult to
narrow down the list of possible causes.
 Maximize useful information and ease of interpretation - It is obvious that maximizing useful
information is desirable, and that it should be easy to interpret. Ease of interpretation is important
in data structures. Some module errors cannot easily be detected by adding code checks because
they depend on the entire structure. Thus it is important to be able to display the structure in a
form that can be easily scanned for correctness.
 Minimize useless and distracting information - Too much information can be as much of a
handicap as too little. If we have to work with a printout that shows entry and exit from every
procedure in a module then we will find it very difficult to find the first place where something
went wrong. Ideally, module execution state reports should be issued only when an error has
occurred. As a general rule, debugging information that says "the problem is here" should be
preferred in favor of reports that say "the problem is not here".
28
Regulation 2023
Academic Year 2024-25
 Avoid complex one-use testing code - One reason why it is counterproductive to add module
correctness checks for errors that involve the entire structure is that the code to do so can be
quite complex. It is very discouraging to spend several hours debugging a problem, only to find
that the error was in the debugging code, not the module under test. Complex testing code is only
practical if the difficult parts of the code are reusable.

Debugging Aids
The debugging aids are built into programming language. Some of them are given below:
 Assert statements - Some Pascal compilers and all C compilers that meet the ANSI standard
have procedures called assert. The assert procedure has a single parameter, which is a Boolean
expression. When a call to assert is executed the expression is evaluated. If it evaluates to true
then nothing happens. If it evaluates to false then the program terminates with an error message.
The assert procedure can be used for detecting and reporting error conditions.
 Tracebacks - Many Pascal compilers generate code that results in tracebacks whenever a runtime
error occurs. A traceback is a report of the sequence of subroutines that are currently active.
Sometimes a traceback will also indicate line numbers in the active subroutines. If available, a
traceback reveals where the runtime error occurred, but it is up to the programmer to determine
where the cause lies.
 General purpose debuggers - Many computer systems or compilers come with debugging
programs. For example, most UNIX operating systems have general purpose debuggers such as
sdb and dbx. Debugging programs provide capabilities for stepping through a program line-by-
line and running a program with breakpoints set by the user. When a line with a breakpoint is
about to be executed the program is interrupted so that the user can examine or modify program
data. Debugging programs also can provide tracebacks in case of run-time errors. Debuggers are
often difficult to learn to use effectively. If they are the only tool used for debugging then it is
likely that they will not save much time. For example, debugging a data structure module with a
debugger, but without a good test driver, will likely result in spending a lot of time getting
piecemeal information about errors.
 Print Statements- Programmers can insert print statements in the code to examine the value of
certain variables in different parts in the program. This enables them to check the value of a
variable and ensure whether it is being modified or not and if being modified, then the current
value if correct or not
Debugging in python IDLE
Debugging is an important activity and python IDLE has a built-in debugger to help debug
programs. The debugger allows the programmer to step through a program and see how the variables
changes values. To use the debugger, start the IDLE and open the program to debug. Then follow the
steps given below
1. In the Shell window, click on the Debug menu option at the top and then on Debugger. Then,
it will show a "Debug Control" window

29
Regulation 2023
Academic Year 2024-25

For the debugger to be most useful, we need to set a breakpoint in our source code before we
start running the program. A breakpoint is a marker on the source code that tells the debugger to
run to this point at normal speed and then pause and let the programmer have control over the
program. As a programmer, we can have many of breakpoints in our program at different places.

2. To set break point, right click on a line of our source and choose "set breakpoint".

The background of the line click on turns yellow to show the line marked with the
breakpoint.

30
Regulation 2023
Academic Year 2024-25

3. Now press F5 to run the program


Note that the Debug Control window is opened and that the blue line states that the line
"from math import pi" is ready to be executed (the 7 is for line number 7 in the source file).
From this point we can click the Go button near the top of the window. This will make the
program run at normal speed until a breakpoint is encountered (or input is requested or the program
finishes)

We can also use the Step button to step through our code, one line at a time. This button
is used quite a lot. If the line being stepped through has a function call, execution will go to the
first line of the function definition. If the line being stepped through doesn't have a function
call, the line is executed. In either case, then control goes back to the human.
When execute a line that has input in it, the debugger seems to shut down but it has not.
If bring up the Shell window can see that the program is waiting for input. Make sure our cursor
is in the right place on the window and give it some input and press Enter as usual.

4. Continue to click on the Step button till the program execution completes. After completion,
the output window and "Debug Control" window look like as shown below

31
Regulation 2023
Academic Year 2024-25

Explanations of a few other things in the Debug Control window


 Over means that if the statement to be executed has a function call in it, go off and do
the function call without showing any details of the execution or variables, then return
and give the human control again, "step over the function"
 Out assumes there are in some function's code, finish execution of the function at
normal speed, return from the function and then give the human control again, "step out
of the function"
 Quit stops the execution of the entire program
1.14 COMMON ERRORS IN PYTHON
There are several types of errors that can occur in Python. Each type indicates a different kind of
problem in the code, and comprehending these error types is crucial in creating effective Python
applications. The most common types of errors encounter in Python are syntax errors, runtime errors,
logical errors, name errors, type errors, index errors, and attribute errors.

1.14.1 Syntax Errors


A syntax error occurs in Python when the interpreter is unable to parse the code due to the code
violating Python language rules, such as inappropriate indentation, erroneous keyword usage, or
incorrect operator use. Syntax errors prohibit the code from running, and the interpreter displays an
error message that specifies the problem and where it occurred in the code.

Example
x = 10
if x == 10
print("x is 10")
When the above code is executed in an IDE, we get the following output message that describes the
error and the location in the code where it occurred:

File "c:\Users\name\OneDrive\Desktop\demo.py", line 2


If x == 10
^

32
Regulation 2023
Academic Year 2024-25
SyntaxError: expected ':'

It shows that there is a SyntaxError on line 2 of the file demo.py.

Solution
The SyntaxError occurs on line 2 because the if statement is missing a colon : at the end of the line.
The correct code should be:

x = 10
if x == 10:
print("x is 10")
This code will execute correctly and print x is 10 to the console because the SyntaxError has been
fixed.

1.14.2 : Runtime Errors


In Python, a runtime error occurs when the program is executing and encounters an unexpected
condition that prevents it from continuing. Runtime errors are also known as exceptions and can occur
for various reasons such as division by zero, attempting to access an index that is out of range, or
calling a function that does not exist.
Types of runtime errors
Runtime errors can be challenging to debug because they occur at runtime and can be difficult
to reproduce. To fix a runtime error, we need to identify the cause of the error and modify the code to
handle the error or avoid it altogether. Below are some specific types of runtime errors.
1. NameError:
A NameError in Python is raised when the interpreter encounters a variable or function name
that it cannot find in the current scope. This can happen for a variety of reasons, such as misspelling a
variable or function name, using a variable or function before it is defined, or referencing a variable or
function that is outside the current scope. Here's an example of a NameError in Python:
def calculate_sum(a, b):
total = a + b
return total

x=5
y = 10
z = calculate_sum(x, w)
print(z)
When the above code is run in an IDE, we get the following output:
Traceback (most recent call last):
File "c:\Users\name\OneDrive\Desktop\demo.py", line 7, in <module>
Z = calculate_sum(x, w)
^
NameError: name 'w' is not defined
Solution:
This error message indicates that the interpreter could not find the variable w in the current scope. To
fix this error, we need to correct the misspelling of the variable name to y , like so:
def calculate_sum(a, b):
total = a + b
return total

x=5
y = 10
z = calculate_sum(x, y)
33
Regulation 2023
Academic Year 2024-25
print(z)
Now the code will run without any errors, and the output will be 15 , which is the correct result of
adding xand y.

2. TypeError:
In Python, a TypeError is raised when an operation or function is applied to an object of an
inappropriate type. This can happen when trying to perform arithmetic or logical operations on
incompatible data types or when passing arguments of the wrong type to a function. Here's an example
of a TypeError in Python:
x = "10"
y=5
Z=x+y
print(z)
When the above code is executed in an IDE, we get the following error message:
Traceback (most recent call last):
File "c:\Users\name\OneDrive\Desktop\demo.py", line 3, in <module>
Z=x+y
~~^~~
TypeError: can only concatenate str (not "int") to str
Solution:
This error message indicates that we cannot concatenatea string and an integer using the + operator.
To fix this error, we need to convert the integer y to a string before concatenating it with x , like so:
x = "10"
y=5
Z = x + str(y)
print(z)
Here, we have used the str() method to convert our integer to a string. Now the code will run without
any errors, and the output will be 105 , which is the result of concatenating x and y as strings.
3. IndexError
An IndexError is raised in Python when we try to access an index of a sequence (such as
a string, list, or tuple) that is out of range. This can happen when we try to access an element that
doesn't exist in the sequence or when we try to access an element at an index that is greater than or
equal to the length of the sequence. Here's an example of an IndexError in Python:
my_list = [100, 200, 300, 400, 500]
print(my_list[5])
When the above code is executed in an IDE, we get the following error message:
Traceback (most recent call last):
File "c:\Users\name\OneDrive\Desktop\demo.py", line 2, in <module>
print(my_list[p

IndexError: list index out of range


Solution:
This error message indicates that we are trying to access an index that is outside the range of valid
indices for the list. To fix this error, we need to make sure that we are only accessing valid indices of
the list, like so:
my_list = [100, 200, 300, 400, 500]
print(my_list[4])
Now the code will run without any errors, and the output will be 500 , which is the element at index
4 of the list.
4. AttributeError
In Python, an AttributeErroris raised when we try to access an attribute or method of an object
that does not exist or is not defined for that object. This can happen when we misspell the name of an
34
Regulation 2023
Academic Year 2024-25
attribute or method or when we try to access an attribute or method that is not defined for the type of
object we are working with. Here's an example of an AttributeError in Python:
my_string = "Hello, world!"
my_string.reverse()
Output for the above code:
Traceback (most recent call last):
File "c:\Users\name\OneDrive\Desktop\demo.py", line 2, in <module>
my_string.reverse()

AttributeError: 'str' object has no attribute 'reverse'


This error message indicates that we are trying to access an attribute (reverse) that is not defined for
the type of object (str) we are working with.

Solution:
To fix this error, we need to use a different method or attribute that is defined for strings, like [::-1] to
reverse the string:
my_string = "Hello, world!"
reversed_string = my_string[::-1]
print(reversed_string)
Now the code will run without any errors, and the output will be !dlrow ,olleH , which is the reversed
string of my_string.

1.14.3 : Logical Errors


A logical error occurs in Python when the code runs without any syntax or runtime errors but
produces incorrect results due to flawed logic in the code. These types of errors are often caused by
incorrect assumptions, an incomplete understanding of the problem, or the incorrect use of algorithms
or formulas.
Unlike syntax or runtime errors, logical errors can be challenging to detect and fix because the
code runs without producing any error messages. The results may seem correct, but the code might
produce incorrect output in certain situations. Here is an example of a logical error in Python:
def calculate_factorial(n):
result = 1
for i in range(1, n):
result = result * i
return result
print(calculate_factorial(5))
Output:
24
In this example, the function calculate_factorial() is designed to calculate the factorial of a given
number n. So when we run it, let's say for n = 5 , it runs without any problem but gives an output
of 24 instead of 120. The reason is a logical error in the code that causes it to produce incorrect results.
The for loop is iterating from 1to n-1instead of from 1 to n , causing the issue. This means that the
factorial is being calculated incorrectly, resulting in an incorrect output.
Solution
To fix this logical error, we need to change the range of the for loop to include the number n itself.
Here's the corrected code:
def calculate_factorial(n):
result = 1
for i in range(1, n+1):
result = result * i
return result

35
Regulation 2023
Academic Year 2024-25
print(calculate_factorial(5))
Output:
120

36

You might also like