0% found this document useful (0 votes)
2 views

Python Lab Manual Final Students

The document is a laboratory manual for a Python Programming course at Dayananda Sagar College of Engineering, detailing course objectives, outcomes, and a syllabus with experiments. It includes guidelines for students, a vision and mission statement for the institute and department, and specific programming tasks to be completed. The manual emphasizes the development of practical skills in Python programming through various exercises and projects.

Uploaded by

dg5562981
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)
2 views

Python Lab Manual Final Students

The document is a laboratory manual for a Python Programming course at Dayananda Sagar College of Engineering, detailing course objectives, outcomes, and a syllabus with experiments. It includes guidelines for students, a vision and mission statement for the institute and department, and specific programming tasks to be completed. The manual emphasizes the development of practical skills in Python programming through various exercises and projects.

Uploaded by

dg5562981
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

PYTHON PROGRAMMING AND ITS APPLICATIONS LAB

MANUAL
IV Semester (22EEL473)

Name of the Student:

Semester/Section :

USN :

Batch :

DAYANANDA SAGAR COLLEGE OF ENGINEERING


(An Autonomous Institute Affiliated to VTU, Belagavi)

Accredited by National Assessment & Accreditation Council (NAAC) with ’A’ Grade
&
(ISO 9001:2015 Certified)

ELECTRICAL & ELECTRONICS ENGINEERING DEPARTMENT


SHAVIGE MALLESWARA HILLS, KUMARASWAMY LAYOUT
Vision of the Institute

To impart quality technical education with a focus on


Research and Innovation emphasizing on Development
of Sustainable and Inclusive Technology for the benefit of
society.

Mission of the Institute

• To provide an environment that enhances creativity


and Innovation in pursuit of Excellence.

• To nurture teamwork in order to transform


individuals as responsible leaders and
entrepreneurs.

• To train the students to the changing technical


scenario and make them to understand the
importance of Sustainable and Inclusive
technologies.
DAYANANDA SAGAR COLLEGE OF ENGINEERING
(An Autonomous Institute Affiliated to VTU, Belagavi)

DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING


BENGALURU - 560111

VISION OF THE DEPARTMENT


To meet the challenging needs of society by innovation, problem solving and to
develop an exciting and supportive learning environment that transforms our
students and inspires them to make a real difference in their career and society.

MISSION OF THE DEPARTMENT


✓ To provide enduring learning environment that facilitates the students to
pursue their higher education.

✓ To train students with diverse skills to work professionally in several


fields through innovative teaching and learning process.

✓ To provide value based and behavioral training programs that helps


students in developing their overall professional competence and social
awareness.

PROGRAMME EDUCATIONAL OBJECTIVES [PEOs]


PEO-1: Graduates will have the ability to apply the knowledge of Electrical & Electronics
Engineering to excel in their career path.

PEO-2: Graduates will be confident to work in flexible and diverse professional fields.

PEO-3: Graduates will have commitment and awareness to thrive in their ethical and social
responsibilities.

PEO-4: Graduates will have the ability to pursue higher education.

PROGRAMME SPECIFIC OUTCOMES [PSOs]


PSO-1:The students will be able to apply the knowledge of mathematics, and applied science
principles to solve diverse problems in the field of Power systems and Control of Electric Drives
catering to Industrial, Research, Service and allied areas.

PSO-2:The students would be competent in identifying, analyzing and exhibiting the skills in
providing solutions to problems related to control electronic systems using various modern tools.

PSO-3: The students will be able to demonstrate proficiency in design and development of different
electrical and electronic systems as per specified standards.
DAYANANDA SAGAR COLLEGE OF ENGINEERING
(An Autonomous Institute Affiliated to VTU, Belagavi)

DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING


BENGALURU-560111

PYTHON PROGRAMMING AND ITS APPLICATIONS


LABORATORY MANUAL (SYLLABUS)

IV SEMESTER B. E (E & EE)

Sub. Code: 22EEL473 IA Marks: 50

Hrs/Week: 2 Exams Hrs: 2

Total Hrs: 32 Exam Marks: 50

Course Objective:
● Understand basic python syntax
● Understand the usage of conditional and looping operations
● Understand the use of functions in python
● Write python programs for simple applications

Course Outcomes:
At the end of the course, student will be able to:

CO 1 Understand the syntax of python programming .

CO 2 Analyze and debug a given python program .

CO 3 Develop programs utilizing the various features of python programming.

CO 4 Design solutions using python of a given problem statement .


Syllabus
Experiment CO’s/Bloom’s
Contents of the Module Hours
No. level

CYCLE 1

1 Introduction to python programming. Introduction to 02 1/L3


IDE, python versions . Datatypes in python. Basic
programs of printing the various datatypes and
performing basic arithmetic operations

2 Revision of conditional statement, looping, logical and 02 1/L3


comparison operators.
a. Find average of a given set of numbers
3 02 2/L3
b. Find the highest average of 2 numbers in given
set of 3 numbers
c. Finding if a number is palindrome or not. (Using
number as a string and as a number both)
a. Print the fibonacci series .
4 02 2/L4
b. Find if a given number is prime or not .
c. Find if a given year is a leap year.

5 Base conversion form octal to hexa , hexa to octal, 02 3/L4


binary to decimal and decimal to binary.
Write programs to generate following patterns in the
6 02 3/L4
output

CYCLE 2

7 Given a sentence, find the number of (a) words in it (b 02 3/L4


) Numbers in it (c) Upper case Characters in it (d) Lower
case characters in it.
a. Given a list of names and a list of phone numbers,
8 02 3/L3
create a dictionary with phone number as key
and name as value
b. Given a sentence, create a dictionary with word
as the key and length of the word as the value.
9 Searching algorithms : Linear Search, Binary Search 02 4/L3

10 Sorting algorithms : Bubble sort, Insertion Sort , Merge 02 4/L4


Sort

11 Develop a python program to play a simple version of 02 4/L4


Hangman game.

12 Develop a python program to create a text based 02 4/L4


calculator with advanced operations like sin,cos etc
included.
DAYANANDA SAGAR COLLEGE OF ENGINEERING
DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING
BENGALURU – 560111

PYTHON PROGRAMMING AND ITS APPLICATIONS LABORATORY


(IV-SEM)

DO’s

➢ DO WEAR UNIFORM & GET YOUR MANNUAL, RECORDS AND


ABSERVATION TO ALL THE SESSIONS.

➢ SAVE ALL THE PROGRAMS IN THE APPROPRIATE DIRECTORY BEFORE


SHUTDOWN THE SYSTEM.

➢ COME PREPARED FOR VIVA & DISCUSS THE PROBLEMS WITH THE STAFF.

➢ EXECUTE THE PROGRAMS AND NOTE DOWN THE RESULTS IN THE


OBSERVATION BOOK.

➢ RETURN ALL THE INTERFACING KITS SAFELY BEFORE LEAVING THE LAB.

➢ BEFORE LEAVING THE LAB GET YOUR OBSERVATION BOOK CORRECTED


AND SHUTDOWN & COVER THE SYSTEMS.

DONT’s

➢ DO NOT SWITCH ON THE SUPPLY WITHOUT THE PERMISSION OF THE


FACULITY.
➢ DO NOT OPEN THE FILES WHICH ARE NOT RELVENT TO YOUR FILES.
➢ DO NOT BRING MOBILE PHONES, MUSIC GADGETS TO THE LAB.
➢ DO NOT COME LATE TO THE LAB MAINTAIN PUNCHUALITY & DISCIPLINE.
DAYANANDA SAGAR COLLEGE OF ENGINEERING
(An Autonomous Institute Affiliated to VTU, Belagavi)

DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING


PYTHON PROGRAMMING AND ITS APPLICATIONS LABORATORY (22EEL473)

EXPT. TITLE OF EXPERMIENT PAGE


NO NO
CYCLE – I

1 Introduction to python programming. Introduction to IDE, python versions .


Datatypes in python. Basic programs of printing the various datatypes and
performing basic arithmetic operations

2 Revision of conditional statement, looping, logical and comparison operators.

3 a. Find average of a given set of numbers


b. Find the highest average of 2 numbers in given set of 3 numbers
c. Finding if a number is palindrome or not. (Using number as a string and
as a number both)

4 a. Print the fibonacci series .


b. Find if a given number is prime or not .
c. Find if a given year is a leap year.

5 Base conversion form octal to hexa , hexa to octal, binary to decimal and
decimal to binary.

6 Write programs to generate following patterns in the output

CYCLE – II

8 Given a sentence, find the number of (a) words in it (b ) Numbers in it (c) Upper
case Characters in it (d) Lower case characters in it.

9 a. Given a list of names and a list of phone numbers, create a dictionary


with phone number as key and name as value
b. Given a sentence, create a dictionary with word as the key and length
of the word as the value.

10 Searching algorithms : Linear Search, Binary Search


11 Sorting algorithms : Bubble sort, Insertion Sort , Merge Sort

12 Develop a python program to play a simple version of Hangman game.

13 Develop a python program to create a text based calculator with advanced


operations like sin,cos etc included.
Python and its Applications Lab Manual (22EEL473)

EXPERIMENT -1
Introduction to python programming. Introduction to IDE, python versions . Datatypes in
python. Basic programs of printing the various datatypes and performing basic arithmetic
operations, logical and conditional operations.

Download Python from : https://www.python.org/downloads/

We will use Python 3.10 for this lab.

Steps for installing python.

1. Double click on the setup that was downloaded.


2. Click next to continue with the installation.
3. Verify the installation by launching the command prompt
4. Type : python --version
5. If you see the python version printed, python installation is successful.
6. If you see an error message check the environmental variables has path to python bin
directory
7. Repeat steps 4,5,6 till the installation is successful.

Integrated Development Environment (IDE) : Anaconda

Download Anaconda from : https://www.anaconda.com/download


You can also use the Anaconda Cloud based notebook as an option.

Python comes with a default editor : IDLE which can also be used.

Department of Electrical and Electronics Engg., D.S.C.E Page No.1


Python and its Applications Lab Manual (22EEL473)
Python Datatypes

Function to Print values on screen : print()

Example :
print(“Hello world”)

Department of Electrical and Electronics Engg., D.S.C.E Page No.2


Python and its Applications Lab Manual (22EEL473)
print(“10”)

Anything passed in double quotes is printed as it is.

Creating Variables :

Variables : A name assigned to a value that has to be stored as part of the program. The variable
is assigned a memory location and any data stored in the variable gets saved in the allocated
memory. The memory allocation is done automatically .

Variable names can be any string that does not start with a Number. It can contain _ as part of the
name.

Example :

x=10
A12=30
x_Y=”abc”

Printing Variables :

print( x)
print(A12)
print(x_Y)

Printing string and variable together :

print(“The value of x is “ , x)
print(“The value of A12 is “ , A12)
print(“The value of x_Y is “ , x_Y)

Department of Electrical and Electronics Engg., D.S.C.E Page No.3


Python and its Applications Lab Manual (22EEL473)

Exercise :
Create variables to hold an integer , a floating point number , a character and a
string value . Print each of them along with the name of the variable.

Test case 1 :

integ=1
flt=1.4
charc=”c”
strin=”abc”

Output :

Test case 2 :

integ=100
flt=2.5
charc=”1”
strin=”hello”

Basic Arithmetic Operations

Variable1 Variable2 Operation Python Code

x=10 y=20 Addition add=x+y

x=10 y=20 Subtraction sub=x-y

x=10 y=20 Multiplication mul=x*y

x=10 y=20 Division div=x/y

x=10 y=20 Floor flt=x//y

x=10 y=20 Power pwr=x**y

Department of Electrical and Electronics Engg., D.S.C.E Page No.4


Python and its Applications Lab Manual (22EEL473)

Exercise :

Write a program to print all the above arithmetic operations.

Logical operators

Logical Operation Description Python Code Output


Returns true if
Returns True if Both both X and Y are
AND Conditions are True X and Y true
Returns true if
Returns True if one of the both X and Y are
OR Conditions is True X or Y true

Returns the Complement of Returns the


NOT the input not X complement of X

Conditional Operations: Execute a certain part of the program only when a condition is true.

If else statements:

Department of Electrical and Electronics Engg., D.S.C.E Page No.5


Python and its Applications Lab Manual (22EEL473)

Ternary operator:

Try:

1. Check if a number is positive or negative.


2. Find maximum of two numbers.
3. Convert number to its absolute value.
4. Calculate the maximum of three numbers.

Department of Electrical and Electronics Engg., D.S.C.E Page No.6


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT -2
Revision of looping, list, tuple, dictionary and sets in python.

1.for loop:

2. while loop:

To print th first 10 natural numbers:

Python program to calculate the sum of all numbers from 1 to a given number.

Department of Electrical and Electronics Engg., D.S.C.E Page No.7


Python and its Applications Lab Manual (22EEL473)

Python program to count the total number of digits in a number.

Calculate the sum of numbers until user enters 0.

Department of Electrical and Electronics Engg., D.S.C.E Page No.8


Python and its Applications Lab Manual (22EEL473)

Try:
1.Python program to calculate the sum of all the odd numbers within the given range.
2. Program to Compute the average of numbers given by user.
3. Program to print the countdown timer starting from 20.

LISTS:

Lists in Python are ordered, mutable (modifiable), and versatile data structures that can contain
elements of different data types. They are defined by enclosing comma-separated values within
square brackets [ ].

Department of Electrical and Electronics Engg., D.S.C.E Page No.9


Python and its Applications Lab Manual (22EEL473)
List comprehension:

Tuple in python:

In Python, a tuple is an ordered collection of elements, similar to a list. However, tuples are
immutable, meaning once created, their elements cannot be changed or modified. Tuples are
defined by enclosing comma-separated values within parentheses ( ).
You can create tuples in Python by enclosing comma-separated values within parentheses.

Tuple packing:

Tuples are immutable, meaning you cannot modify their elements after creation. However, you
can create new tuples by concatenating or slicing existing tuples.

Department of Electrical and Electronics Engg., D.S.C.E Page No.10


Python and its Applications Lab Manual (22EEL473)

Dictionaries in python:
In Python, a dictionary is a collection of key-value pairs. It is unordered, mutable, and indexed.
Dictionaries are defined by enclosing comma-separated key-value pairs within curly braces { },
where each key is associated with a value using a colon :.

Modifying and adding elements:

Removing elements:
You can remove a key-value pair from a dictionary using the del keyword or the pop() method.

Common Dictionary Methods:


keys(): Returns a view object that displays a list of all the keys in the dictionary.
values(): Returns a view object that displays a list of all the values in the dictionary.
items(): Returns a view object that displays a list of key-value tuple pairs.
get(): Returns the value for the specified key. If the key does not exist, it returns a default value
(None by default).
update(): Updates the dictionary with the key-value pairs from another dictionary or iterable.

Department of Electrical and Electronics Engg., D.S.C.E Page No.11


Python and its Applications Lab Manual (22EEL473)

Sets:
In Python, a set is an unordered collection of unique elements. Sets are defined by enclosing
comma-separated elements within curly braces { }. Here's an overview of sets in Python along with
some common operations:
You can create sets in Python by enclosing comma-separated elements within curly braces.
my_set = {1, 2, 3, 4, 5}
mixed_set = {1, "two", 3.0, True}

You cannot access elements of a set using indexing, as sets are unordered. However, you can
check for membership using the in keyword.

Adding or removing elements:

Set Operations:
Union: Returns a set containing all the distinct elements from both sets.
Intersection: Returns a set containing only the elements that are common to both sets.
Difference: Returns a set containing the elements present in the first set but not in the second set.
Symmetric Difference: Returns a set containing elements that are in either of the sets, but not in
both.

Department of Electrical and Electronics Engg., D.S.C.E Page No.12


Python and its Applications Lab Manual (22EEL473)

Set Methods:
add(): Adds an element to the set.
remove(): Removes the specified element from the set. Raises a KeyError if the element is not
present.
discard(): Removes the specified element from the set, if present. Does not raise an error if the
element is not present.
clear(): Removes all elements from the set.
copy(): Returns a copy of the set.

Try:
1.Count even numbers in a list.
2. Remove dupicate elements from a list.
3.check whether the given number is present or not in a tuple
4. Sort a dictionary values by a key
5. Check if a key exists in a dictionary

Department of Electrical and Electronics Engg., D.S.C.E Page No.13


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT -3
3a. Find average of a given set of numbers

Algorithm :

1. Initialize number1 to a numeric value.


2. Initialize number2 to a numeric value.
3. Calculate the sum of number1 and number2, store the result in total_sum.
4. Calculate the average by dividing total_sum by 2, store the result in average.
5. Print the message "Average of the given numbers:" followed by the value of average.

3 b . Find the highest average of 2 numbers in given set of 3 numbers

Algorithm:
1. Initialize three variables num1, num2, and num3 with numeric values.
2. Calculate the average of num1 and num2, store the result in a variable avg1.
3. Calculate the average of num1 and num3, store the result in a variable avg2.
4. Calculate the average of num2 and num3, store the result in a variable avg3.
5. Initialize a variable highest_avg to store the highest average found so far, set it to avg1.
6. Check if avg2 is higher than highest_avg, if so, update highest_avg to avg2.
7. Check if avg3 is higher than highest_avg, if so, update highest_avg to avg3.
8. Print the message "Highest average of two numbers in the given set of three numbers:"
followed by the value of highest_avg.

3c. Write a program to find if a given number is a palindrome or not.

Algorithm :

1. Define the number to be checked, denoted as num.


2. Store the original value of the number in a separate variable, denoted as original_num.
3. Initialize a variable to store the reversed number, denoted as reversed_num, with an initial
value of 0.
4. Reverse the digits of the number using a loop:
5. While num is greater than 0:
6. Extract the last digit of num using modulo 10, store it in a variable digit.
7. Append digit to the reversed_num by multiplying reversed_num by 10 and adding digit.
8. Remove the last digit from num by integer division with 10.
9. Check if the reversed number (reversed_num) is equal to the original number
(original_num).
10. If the numbers are equal, print "The number is a palindrome."
11. If the numbers are not equal, print "The number is not a palindrome."

Department of Electrical and Electronics Engg., D.S.C.E Page No.14


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT -4
4a . Print the fibonacci series .

Algorithm :
1. Initialize the first number in the Fibonacci sequence, denoted as num1, with a value of 0.
2. Initialize the second number in the Fibonacci sequence, denoted as num2, with a value of
1.
3. Print the value of num1.
4. Print the value of num2.
5. Loop to generate the Fibonacci sequence up to the desired term:
6. For each iteration from 1 to 10 (inclusive):
7. Calculate the next number in the sequence by adding num1 and num2, store the result in a
variable num3.
8. Print the value of num3.
9. Update num1 to be the value of num2 for the next iteration.
10. Update num2 to be the value of num3 for the next iteration.

4b. Write a program to find if a given number is Prime or not .

Algorithm :

1. Assign a value to the variable num, representing the number to be checked for primality.
2.Initialize a variable prime to 0, assuming the number is prime initially.
3. Iterate through numbers from 2 to num - 1.
4. Check if num is divisible by the current number.
5. If num is divisible by any number in the range, set prime to 1 (indicating the number is not
prime).
6. After the loop, check if prime is still 0.
7. If prime is 0, print that the number is prime.
8. If prime is not 0, print that the number is not prime.

4c. Write a Program to Find if a given year is Leap year or not.

Algorithm

1. Initialize a variable year with a numeric value representing the year to be checked.
2. Check if the year is divisible by 4 and not divisible by 100, or if it is divisible by 400:
3. If the condition is true, the year is a leap year.
4. If the condition is false, the year is not a leap year.
5. Print a message indicating whether the year is a leap year or not.

Department of Electrical and Electronics Engg., D.S.C.E Page No.15


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT 5:
5a. . Base conversion from octal to hexadecimal.

Algorithm:
1. Input: Receive an octal number.
2. Convert Octal to Decimal:
❖ Initialize a variable decimal_num to store the decimal equivalent, starting from 0.
❖ Initialize a variable power to keep track of the position of each digit in the octal number,
starting from 0.
❖ Iterate through each digit of the octal number from right to left:
Extract the last digit of the octal number.
Multiply the last digit by power of 8 and add it to decimal_num.
Increment power by 1.
Remove the last digit from the octal number.
At the end of the iteration, decimal_num will hold the decimal equivalent of the octal
number.
3. Convert Decimal to Hexadecimal:
❖ Initialize an empty string hexadecimal_num to store the hexadecimal representation.
❖ Define a string hexadecimal_chars containing the hexadecimal characters
"0123456789ABCDEF".
❖ While decimal_num is not zero:
Find the remainder when decimal_num is divided by 16.
Use the remainder as an index to retrieve the corresponding hexadecimal character from
hexadecimal_chars.
Prepend the retrieved character to hexadecimal_num.
Divide decimal_num by 16, discarding any remainder.
At the end of the iteration, hexadecimal_num will hold the hexadecimal representation of
the decimal number.
4. Output: Display hexadecimal_num as the hexadecimal equivalent of the input octal
number.

Description:
This program consists of three functions:

1. octal_to_decimal: This function takes an octal number as input and converts it to decimal
using the positional notation method. It iterates through each digit of the octal number,
multiplying it by the corresponding power of 8 and summing up the results.

2. decimal_to_hexadecimal: This function takes a decimal number as input and converts it to


hexadecimal. It repeatedly divides the decimal number by 16 and keeps track of the
remainders. Each remainder corresponds to a hexadecimal digit, which is then
concatenated to form the hexadecimal representation.

3. octal_to_hexadecimal: This function combines the above two functions to convert an octal
number to hexadecimal. It first converts the octal number to decimal using
octal_to_decimal, and then converts the decimal number to hexadecimal using
decimal_to_hexadecimal.

Department of Electrical and Electronics Engg., D.S.C.E Page No.16


Python and its Applications Lab Manual (22EEL473)
Finally, there's a test portion where the user is prompted to input an octal number, which is then
converted to hexadecimal using the octal_to_hexadecimal function and displayed as output.

5.b. Base conversion from hexa to octal


Algorithm:
1. Input: Receive a hexadecimal number.
2. Convert Hexadecimal to Decimal:
❖ Initialize a variable decimal_num to store the decimal equivalent, starting from 0.
❖ Initialize a variable power to keep track of the position of each digit in the hexadecimal
number, starting from 0.
❖ Iterate through each digit of the hexadecimal number from right to left:
Find the index of the current digit in the string "0123456789ABCDEF".
Multiply this index by 16 power and add it to decimal_num.
Increment power by 1.
At the end of the iteration, decimal_num will hold the decimal equivalent of the
hexadecimal number.
3. Convert Decimal to Octal:
❖ Initialize an empty string octal_num to store the octal representation.
❖ While decimal_num is not zero:
Find the remainder when decimal_num is divided by 8.
Prepend this remainder to octal_num.
Divide decimal_num by 8, discarding any remainder.
At the end of the iteration, octal_num will hold the octal representation of the decimal
number.
4. Output: Display octal_num as the octal equivalent of the input hexadecimal number.

Description:

Below is a step-by-step explanation of the algorithm implemented in these functions:

hexadecimal_to_decimal(hexadecimal_num):

Initialize decimal_num to 0 to hold the decimal equivalent.


Initialize power to 0 to keep track of the position of each hexadecimal digit.
Iterate through each digit of the hexadecimal number from right to left.
For each digit:
Find its corresponding decimal value by getting its index in the hexadecimal_chars string (which
contains the hexadecimal digits).
Multiply this value by 16 power and add it to decimal_num.
Increment power by 1.
Return decimal_num as the decimal equivalent of the hexadecimal number.

decimal_to_octal(decimal_num):
Initialize an empty string octal_num to hold the octal representation.
While decimal_num is not zero:
Find the remainder when decimal_num is divided by 8.
Prepend this remainder to octal_num.
Divide decimal_num by 8, discarding any remainder.
Return octal_num as the octal representation of the decimal number.

Department of Electrical and Electronics Engg., D.S.C.E Page No.17


Python and its Applications Lab Manual (22EEL473)
hexadecimal_to_octal(hexadecimal_num):

Convert the hexadecimal number to its decimal equivalent using the hexadecimal_to_decimal
function.
Convert the decimal number to its octal equivalent using the decimal_to_octal function.
Return the octal representation of the hexadecimal number.
The test portion of the code prompts the user to input a hexadecimal number, converts it to octal
using the hexadecimal_to_octal function, and prints the result.

5.c. binary to decimal

Algorithm:
1. Input: Receive a binary number.
2. Initialize Variables:
❖ Initialize a variable decimal_num to store the decimal equivalent, starting from 0.
❖ Initialize a variable power to keep track of the position of each digit in the binary number,
starting from 0.

3. Convert Binary to Decimal:


❖ Iterate through each digit of the binary number from right to left:
Extract the last digit of the binary number.
Multiply this digit by power of 2 and add it to decimal_num.
Increment power by 1.
Remove the last digit from the binary number.
At the end of the iteration, decimal_num will hold the decimal equivalent of the binary
number.
4. Output: Display decimal_num as the decimal equivalent of the input binary number.

This algorithm follows a straightforward approach to convert each digit of the binary number to its
decimal equivalent and summing them up to get the final result.

5.d. decimal to binary

Algorithm:
Here's the step-by-step algorithm to convert a decimal number to its binary equivalent:
1. Input: Receive a decimal number.
Special Case: Decimal Number 0:
If the decimal number is 0, return "0" as the binary equivalent.
2. Initialize Variables:
Initialize an empty string binary_num to store the binary representation.
3. Convert Decimal to Binary:
While the decimal number is greater than 0:
Find the remainder when the decimal number is divided by 2.
Prepend the remainder to binary_num.
Divide the decimal number by 2, discarding any remainder.
At the end of the iteration, binary_num will hold the binary representation of the decimal
number.
4. Output: Display binary_num as the binary equivalent of the input decimal number.

Department of Electrical and Electronics Engg., D.S.C.E Page No.18


Python and its Applications Lab Manual (22EEL473)

This algorithm follows a simple iterative process of continuously dividing the decimal number by 2
and appending the remainders to construct the binary representation from right to left

Description:
❖ This program defines a function decimal_to_binary that takes a decimal number as input
and returns its binary equivalent.
❖ It iteratively divides the decimal number by 2 and keeps track of the remainders, which
represent the binary digits.
❖ The remainders are prepended to an empty string to construct the binary representation.
❖ Finally, it prompts the user to input a decimal number, checks if the input is negative
(which is not supported for this conversion), and prints its binary equivalent if the input is
valid.

Department of Electrical and Electronics Engg., D.S.C.E Page No.19


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT 6
Write programs to generate following patterns in the output.

6. a. Butterfly pattern:
Algorithm:
1. Input: Receive the size of the butterfly pattern.
2. Upper Wing:
❖ Iterate from 1 to the size:
Print stars (*) from 1 to the current iteration index.
Print spaces ( ) from 1 to 2 times the difference between the size and the current index.
Print stars (*) from 1 to the current iteration index.

3. Lower Wing:
❖ Iterate from size - 1 down to 1:
Print stars (*) from 1 to the current iteration index.
Print spaces ( ) from 1 to 2 times the difference between the size and the current index.
Print stars (*) from 1 to the current iteration index.
4. Output: Display the butterfly pattern.

6. b. Hourglass pattern
Algorithm:
1. Input: Receive the size of the hourglass pattern.

2. Upper Half of the Hourglass:

Iterate from size down to 1:


Print spaces to shift the stars to the right.
Print stars, where the number of stars on each line decreases by 2 with each
iteration.

3. Lower Half of the Hourglass:

Iterate from 2 to size:


Print spaces to shift the stars to the right.
Print stars, where the number of stars on each line increases by 2 with each
iteration.
4. Output: Display the hourglass pattern.

Department of Electrical and Electronics Engg., D.S.C.E Page No.20


Python and its Applications Lab Manual (22EEL473)
6.c. to print the diamond

Algorithm:
1. Input the size of the diamond (number of rows).
2. Print the upper half of the diamond:
Iterate over the rows from 1 to the specified size, incrementing by 2 in each iteration.
On each row, print spaces and then asterisks in a pattern such that the number of asterisks
increases from 1 to the specified row number.

3. Print the lower half of the diamond (including the center line):
Iterate over the rows from size - 2 down to 1, decrementing by 2 in each iteration.
On each row, print spaces and then asterisks in a pattern such that the number of asterisks
decreases from the specified size - 2 to 1.
4. End

6 .d. Equilateral triangle of 1,3,5,7,9,11 stars

Algorithm:
1. Input the size of the triangle (number of rows).
2. Iterate over each row from 0 to size - 1:
Calculate the number of spaces required for each row as size - row - 1.
Calculate the number of stars required for each row as 2 * row + 1.
3. Print the required number of spaces followed by the required number of stars.
4. End

Department of Electrical and Electronics Engg., D.S.C.E Page No.21


Python and its Applications Lab Manual (22EEL473)

Experiment 7
Given a sentence, find the number of (a) words in it
(b ) Numbers in it
(c) Upper case Characters in it
(d) Lower case characters in it

Algorithm:
1. Input the sentence.
2. Initialize counters for each category (words, numbers, uppercase characters, lowercase
characters) to zero.
3. Split the sentence into words.
4. Iterate over each word:
Check if the word is a number:
If yes, increment the number counter.
5. Check each character in the word:
If the character is uppercase:
Increment the uppercase character counter.
6. If the character is lowercase:
Increment the lowercase character counter.
After iterating over all words, count the total number of words.
7. Output the counts of words, numbers, uppercase characters, and lowercase characters.
8. End

Department of Electrical and Electronics Engg., D.S.C.E Page No.22


Python and its Applications Lab Manual (22EEL473)

Experiment 8
8 a. Given a list of names and a list of phone numbers, create a dictionary with phone number as
key and name as value.

Algorithm:
1. Input the list of names and the list of phone numbers.
2. Initialize an empty dictionary to store the phonebook.
3. Iterate over each pair of name and phone number from the input lists:
Map each name to its corresponding phone number as a key-value pair in the dictionary.
4. Output the phonebook dictionary.
5. End.

8.b. Given a sentence, create a dictionary with word as the key and length of the word as the
value.

Algorithm:

1. Input the sentence.


2. Split the sentence into words.
3. Initialize an empty dictionary to store the word lengths.
4. Iterate over each word:
Calculate the length of each word.
Map each word to its length as a key-value pair in the dictionary.
5. Output the dictionary with words as keys and their lengths as values.
6. End.

Department of Electrical and Electronics Engg., D.S.C.E Page No.23


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT 9
9.a. Linear search in an array

Linear search is a simple searching algorithm that sequentially checks each element in a list or
array until the desired element is found or until all elements have been searched.

Algorithm:

1. Input the list of elements to be searched and the target element to be found.
2. Initialize a variable found to False.
3. Iterate over each element in the list:
Check if the current element is equal to the target element:
If yes, set found to True and break out of the loop.
If the target element is found (i.e., found is True), output the index of the element in the
list.
If not found, output a message indicating that the target element is not present in the list.
4. End.

9. B. Binary search in an array

Binary search is a searching algorithm used to find the position of a target value within a sorted
array. It works by repeatedly dividing the search interval in half until the target value is found or
the interval is empty.

Here's an algorithm for binary search:

1. Input the sorted array and the target value to be found.


2. Initialize variables left and right to represent the leftmost and rightmost indices of the
search interval, respectively.
3. While left is less than or equal to right:
Calculate the middle index of the search interval as (left + right) // 2.
❖ If the target value is equal to the value at the middle index, return the middle index
as the position of the target value.
❖ If the target value is less than the value at the middle index, update right to be one
less than the middle index (i.e., right = mid - 1).
❖ If the target value is greater than the value at the middle index, update left to be
one more than the middle index (i.e., left = mid + 1).
❖ If the target value is not found in the array, return -1 to indicate that the target
value is not present.
4. End.

Department of Electrical and Electronics Engg., D.S.C.E Page No.24


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT 10
Sorting algorithms

10.a. Bubble sort


Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the wrong order. The pass through the list is repeated
until the list is sorted.

Here's an algorithm for bubble sort:

1. Input the list of elements to be sorted.


2. Repeat the following steps for each element in the list:
Iterate over the list from index 0 to index n-1, where n is the length of the list:
Compare each pair of adjacent elements.
If the elements are in the wrong order (i.e., the element at index i is greater than the
element at index i+1), swap them.
3. Repeat the above step for n-1 passes, where n is the length of the list.
4. Output the sorted list.
5. End.

10. b. Insertion sort

Insertion sort is a simple sorting algorithm that builds the final sorted list one element at a time. It
works by iterating over the list and repeatedly moving the current element to its correct position
within the sorted part of the list.

Here's an algorithm for insertion sort:

1. Input the list of elements to be sorted.


2. Iterate over each element in the list starting from the second element (index 1):
❖ For each element, compare it with the elements to its left (sorted part of the list)
until finding the correct position to insert it.
❖ Shift the elements greater than the current element to the right to make space for
the current element.
3. Output the sorted list.
4. End.

Department of Electrical and Electronics Engg., D.S.C.E Page No.25


Python and its Applications Lab Manual (22EEL473)
10. c. Merge sort

Merge sort is a divide-and-conquer algorithm that divides the input list into two halves, sorts each
half recursively, and then merges the sorted halves to produce the final sorted list.

Here's an algorithm for merge sort:

1. Input the list of elements to be sorted.


2. If the length of the list is less than or equal to 1, return the list (base case for recursion).
3. Divide the list into two halves.
4. Recursively apply merge sort to each half.
5. Merge the sorted halves to produce the final sorted list.
6. Initialize an empty list to store the merged result.
7. Compare the first elements of the two sorted halves and append the smaller one to the
result list.
8. Continue comparing and appending elements from both halves until one of the halves is
exhausted.
9. Append the remaining elements from the non-empty half to the result list.
10. Output the final sorted list.
11. End.

Department of Electrical and Electronics Engg., D.S.C.E Page No.26


Python and its Applications Lab Manual (22EEL473)

EXPERIMENT 11
Develop a python program to play a simple version of Hangman game.

EXPERIMENT 12
Develop a python program to create a text based calculator with advanced operations like
sin,cos etc included.

(Experiments 11 and 12 will be group activities with presentations from each group to describe
their codes/algorithms)

Department of Electrical and Electronics Engg., D.S.C.E Page No.27

You might also like