Python Lab Manual Final Students
Python Lab Manual Final Students
MANUAL
IV Semester (22EEL473)
Semester/Section :
USN :
Batch :
Accredited by National Assessment & Accreditation Council (NAAC) with ’A’ Grade
&
(ISO 9001:2015 Certified)
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.
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)
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:
CYCLE 1
CYCLE 2
DO’s
➢ COME PREPARED FOR VIVA & DISCUSS THE PROBLEMS WITH THE STAFF.
➢ RETURN ALL THE INTERFACING KITS SAFELY BEFORE LEAVING THE LAB.
DONT’s
5 Base conversion form octal to hexa , hexa to octal, binary to decimal and
decimal to binary.
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.
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.
Python comes with a default editor : IDLE which can also be used.
Example :
print(“Hello world”)
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)
print(“The value of x is “ , x)
print(“The value of A12 is “ , A12)
print(“The value of x_Y is “ , x_Y)
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”
Exercise :
Logical operators
Conditional Operations: Execute a certain part of the program only when a condition is true.
If else statements:
Ternary operator:
Try:
EXPERIMENT -2
Revision of looping, list, tuple, dictionary and sets in python.
1.for loop:
2. while loop:
Python program to calculate the sum of all numbers from 1 to a given number.
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 [ ].
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.
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 :.
Removing elements:
You can remove a key-value pair from a dictionary using the del keyword or the pop() method.
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.
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.
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
EXPERIMENT -3
3a. Find average of a given set of numbers
Algorithm :
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.
Algorithm :
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.
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.
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.
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.
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.
Description:
hexadecimal_to_decimal(hexadecimal_num):
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.
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.
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.
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.
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.
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.
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.
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
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
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
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:
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.
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.
EXPERIMENT 10
Sorting algorithms
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.
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.
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)