PythonUnit IModule
PythonUnit IModule
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.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']
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
‗ ‗‘ ―‖ # \ ( ) { } [ ] @ , : . ;
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'))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
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'}
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)
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.
# Output
print("Hello, " + name)
print(type(name))
Output:
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
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")
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.
# Declaring a variable
name = "Gfg"
# Output
print(f'Hello {name}! How are you?')
Output:
15
Regulation 2023
Academic Year 2024-25
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.
# 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:
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'
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.
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.
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
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
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
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.
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.
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
26
Regulation 2023
Academic Year 2024-25
# printing character converting to integer
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
# initializing string
s = 'INDIA'
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
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
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:
32
Regulation 2023
Academic Year 2024-25
SyntaxError: expected ':'
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.
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
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.
35
Regulation 2023
Academic Year 2024-25
print(calculate_factorial(5))
Output:
120
36