0% found this document useful (0 votes)
15 views66 pages

Python Lab Handout ECE

The document is a lab manual for a Python Programming course at MVGR College of Engineering, detailing weekly objectives and exercises. It covers fundamental concepts such as data types, operators, control statements, and functions, along with practical programming tasks for students. Each week includes specific programs to be implemented, test cases, and solution explanations to enhance learning.

Uploaded by

bhadrasree10
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)
15 views66 pages

Python Lab Handout ECE

The document is a lab manual for a Python Programming course at MVGR College of Engineering, detailing weekly objectives and exercises. It covers fundamental concepts such as data types, operators, control statements, and functions, along with practical programming tasks for students. Each week includes specific programs to be implemented, test cases, and solution explanations to enhance learning.

Uploaded by

bhadrasree10
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

DEPARTMENT OF ELECTRONICS AND COMMUNICATION

ENGINEERING

MVGR COLLEGE OF ENGINEERING(A)

PYTHON PROGRAMMING LAB

Prepared by

Dr. B. Lavanya, Associate Professor


Mr. N. Shanmuka Rao, Associate Professor
Mr. P. Pavan Kumar. Dist. Assistant Professor
Page 2

Week 1: Data Types, Operators, Built-in Functions


Objective:

This week, we focus on understanding Python's basic data types, operators, and commonly used
built-in functions. The exercises will provide hands-on experience with Python's core concepts.

Program 1: Data Types in Python

Question:
Write a Python script to illustrate the following data types:

• Integer (int)

• Character (char)

• Float (float)

• String (str)

Test Cases:

• Standard Cases:

o Input: x = 5 (Integer)
Expected Output: x is of type <class 'int'>

o Input: y = 3.14 (Float)


Expected Output: y is of type <class 'float'>

o Input: z = 'Hello' (String)


Expected Output: z is of type <class 'str'>

o Input: a = 'C' (Character, treated as string)


Expected Output: a is of type <class 'str'>

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 3

Solution Explanation:

• Python treats characters as strings, so char data type is represented as a single character
string.

• type() function is used to check the data type of the variables.

Program 2: Operator Precedence

Question:
Write a Python program to perform the following expressions, illustrating operator precedence:

1. 5 + 3 * 2

2. 2 * 3**2

3. 2**3**2

4. (2**3)**

Test Cases:

• Standard Cases:

o Input: 5 + 3 * 2
Expected Output: 11

o Input: 2 * 3**2
Expected Output: 18

o Input: 2**3**2
Expected Output: 512

o Input: (2**3)**2
Expected Output: 64

Solution Explanation:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 4

• Operator precedence in Python follows PEMDAS (Parentheses, Exponents,


Multiplication/Division, Addition/Subtraction). For example, 3**2 is computed before 2 *
3**2.

Program 3: Type Conversion Functions

Question:
Write a Python program to demonstrate type conversion using functions such as int(), float(), str(),
etc.

Test Cases:

• Standard Cases:

o Input: int('10')
Expected Output: 10

o Input: float('3.14')
Expected Output: 3.14

o Input: str(5)
Expected Output: '5'

o Input: int(3.99)
Expected Output: 3

Solution Explanation:

• int(), float(), and str() are used to convert between data types.

• int(3.99) truncates the decimal and returns the integer part.

Program 4: Math Module Functions

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 5

Question:
Write a Python program to illustrate the following functions of the math module: pi, sqrt(), cos(), and
sin().

Test Cases:

• Standard Cases:

o Input: [Link]
Expected Output: 3.141592653589793

o Input: [Link](16)
Expected Output: 4.0

o Input: [Link](0)
Expected Output: 1.0

o Input: [Link]([Link] / 2)
Expected Output: 1.0

Program Solution:

Solution Explanation:

• The math module provides mathematical functions and constants.

• [Link] gives the value of π.

• [Link]() returns the square root of a number.

• [Link]() and [Link]() compute the cosine and sine of an angle (in radians).

Additional Notes for Instructors:

• Solution Hints: For each program, students can refer to the math documentation or Python's
official website for more examples and detailed explanations.

• Test Automation: Implementing automated test cases with a test framework (e.g., unittest or
pytest) can help students check their program's correctness.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 6

Week – 2: Programs Without Control Statements


1. Write a program to calculate simple interest

2. Write a python program to calculate compound interest

3. Write a python program to print ASCII value of a character

4. Write a python program to find the area of a circle

5. Write a python program to find the area of a triangle

6. Write a program to perform string concatenation

Week 2: Programs Without Control Statements

Objective:

This week, the focus is on writing programs without using control statements. We will work on basic
calculations, string manipulations, and simple mathematical operations.

Program 1: Calculate Simple Interest

Question:
Write a Python program to calculate simple interest. The formula for simple interest is:

Simple Interest (SI)=P×R×T100\text{Simple Interest (SI)} = \frac{P \times R \times


T}{100}Simple Interest (SI)=100P×R×T

Where:

• PPP is the principal amount,

• RRR is the rate of interest,

• TTT is the time period in years.

Test Cases:

• Standard Cases:

o Input: P = 1000, R = 5, T = 2
Expected Output: Simple Interest = 100.0

o Input: P = 1500, R = 7, T = 3
Expected Output: Simple Interest = 315.0

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 7

Solution Explanation:

• The formula for simple interest is applied directly without any control flow (like if, else,
loops).

• The values of P, R, and T are multiplied and divided as per the formula.

Program 2: Calculate Compound Interest

Question:
Write a Python program to calculate compound interest. The formula for compound interest is:

Compound Interest (CI)=P(1+R100)T−P\text{Compound Interest (CI)} = P \left(1 +


\frac{R}{100}\right)^T - PCompound Interest (CI)=P(1+100R)T−P

Where:

• PPP is the principal amount,

• RRR is the rate of interest,

• TTT is the time period in years.

Test Cases:

• Standard Cases:

o Input: P = 1000, R = 5, T = 2
Expected Output: Compound Interest = 102.5

o Input: P = 1500, R = 7, T = 3
Expected Output: Compound Interest = 349.086

Program Solution:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 8

Solution Explanation:

• The compound interest formula is directly applied using Python's exponentiation operator
**.

• The interest is calculated after applying the formula.

Program 3: ASCII Value of a Character

Question:
Write a Python program to print the ASCII value of a given character. Use the ord() function to find
the ASCII value.

Test Cases:

• Standard Cases:

o Input: 'A'
Expected Output: ASCII value of 'A' = 65

o Input: 'a'
Expected Output: ASCII value of 'a' = 97

o Input: '1'
Expected Output: ASCII value of '1' = 49

Program Solution:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 9

Here's the Lab Manual for Week 2: Programs Without Control Statements:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 10

Week 3: Programs on Numpy Module


Program 1: Working with 1D Array Operations (Indexing and Slicing)

Question:
Write a Python program to perform operations on a 1D NumPy array, including indexing and slicing.

Test Cases:

• Standard Cases:

o Input: arr = [Link]([1, 2, 3, 4, 5])

▪ Indexing: Print the element at index 2.

▪ Slicing: Print elements from index 1 to 3.

o Expected Output:

Element at index 2: 3

Sliced array from index 1 to 3: [2 3 4]

Solution Explanation:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 11

• Indexing: To access an element, you can use the array's index. In this case, arr[2] accesses
the element at index 2.

• Slicing: You can extract a subarray using the slicing syntax. In this case, arr[1:4] returns the
elements from index 1 to 3 (index 4 is excluded).

Program 2: Working with 2D Array Operations

Question:
Write a Python program to perform operations on a 2D NumPy array, including indexing, slicing, and
reshaping.

Test Cases:

• Standard Cases:

o Input: arr2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

▪ Indexing: Print the element at position (1, 2) (second row, third column).

▪ Slicing: Print the first two rows and columns (first two rows and columns).

▪ Reshaping: Convert the array to a 1D array.

Element at position (1, 2): 6 Sliced array (first 2 rows and columns): [[1 2] [4 5]] Reshaped array (1D):
[1 2 3 4 5 6 7 8 9]

Solution Explanation:

• Indexing: arr2d[1, 2] accesses the element in the second row and third column.

• Slicing: arr2d[:2, :2] slices the array to get the first two rows and columns.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 12

• Reshaping: [Link](-1) flattens the 2D array into a 1D array, where -1 allows NumPy to
automatically calculate the size of the new dimension.

Additional Notes for Instructors:

• Solution Hints:

o Indexing: Students should use the correct index format (arr[<row>, <col>]) for 2D
arrays.

o Slicing: Encourage students to experiment with different slice ranges for both 1D and
2D arrays.

o Reshaping: Point out that reshaping does not change the underlying data but just
changes its view.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 13

Week 4: Programs on Control Statements


1. Write a python program find the power of a number without built-in functions.

2. Write a python program to count the number of even and odd numbers upto the given range.

3. Write a python program to print the multiplication table for a given number.

4. Write a python program to display minimum and maximum among three numbers

Objective:

This week, students will focus on learning and implementing control statements in Python. They will
write programs that involve decision-making (if-else) and looping (for, while) constructs to solve
different problems.

Program 1: Finding the Power of a Number Without Built-in Functions

Question:
Write a Python program to calculate the power of a number without using built-in functions.

Test Cases:

• Standard Case:

o Input: base = 2, exponent = 3

▪ Expected Output: 2^3 = 8

o Input: base = 5, exponent = 0

▪ Expected Output: 5^0 = 1

o Input: base = 7, exponent = -2

▪ Expected Output: 7^-2 = 0.0204

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 14

Solution Explanation:

• The power function calculates the power of a number using a loop. If the exponent is
positive, it multiplies the base by itself for the given number of times. If the exponent is
negative, it divides 1 by the base for the absolute value of the exponent.

Program 2: Counting the Number of Even and Odd Numbers Up to a Given Range

Question:
Write a Python program to count the number of even and odd numbers up to a given range.

Test Cases:

• Standard Case:

o Input: range_limit = 10

▪ Expected Output: Even count: 5, Odd count: 5

o Input: range_limit = 15

▪ Expected Output: Even count: 7, Odd count: 8

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 15

Solution Explanation:

• The program loops through the range from 1 to the specified limit. It uses the modulo
operator % to check if the number is divisible by 2, thereby categorizing it as even or odd.

Program 3: Printing the Multiplication Table for a Given Number

Question:
Write a Python program to print the multiplication table for a given number.

Test Cases:

• Standard Case:

o Input: num = 5

▪ Expected Output:

python

Copy code

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 16

5x1=5

5 x 2 = 10

5 x 3 = 15

...

5 x 10 = 50

Program Solution:

Solution Explanation:

• The multiplication_table function iterates from 1 to 10, multiplying the input number by the
loop index i and printing the result in a readable format.

Program 4: Display Minimum and Maximum Among Three Numbers

Question:
Write a Python program to display the minimum and maximum values among three numbers.

Test Cases:

• Standard Case:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 17

o Input: num1 = 10, num2 = 20, num3 = 5

▪ Expected Output: Minimum: 5, Maximum: 20

o Input: num1 = 15, num2 = 25, num3 = 20

▪ Expected Output: Minimum: 15, Maximum: 25

Solution Explanation:

• The program uses Python’s built-in min() and max() functions to find the minimum and
maximum values among the three input numbers.

Additional Notes for Instructors:

• Solution Hints:

o Program 1 (Power): Students can approach this problem by considering both


positive and negative exponents. Using loops for multiplication and division can
simulate exponentiation without using built-in functions.

o Program 2 (Even and Odd Count): Remind students about the modulo operator %,
which is useful for checking divisibility.

o Program 3 (Multiplication Table): This is a simple use case for the for loop. Ensure
students understand how to format output.

o Program 4 (Min and Max): This can also be done with conditionals (if-else), but
Python's built-in functions min() and max() provide an elegant solution.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 18

Week 5: Programs on Functions


1. Write a python program to find if a number is prime or not with and without recursion.

2. Write a python program to display Fibonacci series using iteration and recursion.

3. Write a python program to find the factorial of a number with and without recursion

Objective:

This week, students will learn about functions in Python, focusing on recursion and iteration. They
will write programs that use both types of approaches to solve problems.

Program 1: Checking if a Number is Prime or Not (With and Without Recursion)

Question:
Write a Python program to check if a number is prime or not, both with and without recursion.

Test Cases:

• Standard Case:

o Input: num = 7

▪ Expected Output: 7 is a prime number

o Input: num = 10

▪ Expected Output: 10 is not a prime number

o Input: num = 1

▪ Expected Output: 1 is not a prime number

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 19

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 20

Solution Explanation:

• Without Recursion: The program checks if a number is divisible by any number from 2 to
num-1. If it is divisible by any, it is not prime.

• With Recursion: This program works similarly but uses recursion to check divisibility by
decrementing the divisor until it reaches 1.

Program 2: Displaying Fibonacci Series Using Iteration and Recursion

Question:
Write a Python program to display the Fibonacci series using both iteration and recursion.

Test Cases:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 21

• Standard Case:

o Input: n = 5

▪ Expected Output: Fibonacci Series (Iterative): 0 1 1 2 3

▪ Expected Output: Fibonacci Series (Recursive): 0 1 1 2 3

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 22

Solution Explanation:

• Iterative: The program initializes two variables a and b to represent the first two numbers in
the Fibonacci series and iterates to calculate and append the next numbers.

• Recursive: The program builds the Fibonacci series by calling the function recursively to
calculate previous values and appending the sum of the last two numbers to the series.

Program 3: Finding the Factorial of a Number (With and Without Recursion)

Question:
Write a Python program to find the factorial of a number, both with and without recursion.

Test Cases:

• Standard Case:

o Input: num = 5

▪ Expected Output: 5! = 120

o Input: num = 3

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 23

▪ Expected Output: 3! = 6

o Input: num = 0

▪ Expected Output: 0! = 1

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 24

Solution Explanation:

• Without Recursion: The program calculates the factorial by iterating through the range of
numbers from 1 to the given number and multiplying them together.

• With Recursion: The recursive function calls itself with a decrementing number until it
reaches the base case (0! = 1 or 1! = 1), then multiplies the numbers as the recursion
unwinds.

Additional Notes for Instructors:

• Solution Hints:

o Program 1 (Prime Check): Encourage students to think about both base cases (1 and
numbers less than 1) and the loop/recursion logic for checking divisibility.

o Program 2 (Fibonacci): Make sure students understand how recursion and iteration
can both be used to solve the same problem and discuss the efficiency differences.

o Program 3 (Factorial): Point out the similarities between the iterative and recursive
approaches for calculating factorials and discuss how recursion can be more elegant
but also less efficient for large numbers.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 25

Week 6: Programs on Strings


1. Write a program to work with string built-in functions

2. Write a python program to determine number of times a given letter occurs in a string

3. Write a python program to check if a string is a palindrome or not.

4. Illustrate in operator and write a python program to count number of lowercase characters in a
string. 5. Write a program to replace all the occurrences of letter ‘a’ with letter ‘x’ in a string.

Objective:

This week, students will work with various string operations and built-in functions in Python. The
goal is to practice string manipulation, searching, and replacement techniques using Python’s string
methods.

Program 1: Working with String Built-in Functions

Question:
Write a Python program to illustrate the usage of common string built-in functions such as upper(),
lower(), replace(), split(), join(), and find().

Test Cases:

• Standard Case:

o Input: s = "Hello World"

▪ Expected Output:

▪ Uppercase: HELLO WORLD

▪ Lowercase: hello world

▪ Replaced: Hellx World

▪ Split: ['Hello', 'World']

▪ Find position of 'World': 6

▪ Joined: Hello-World

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 26

Solution Explanation:

• The program demonstrates multiple string functions in Python. Each function is applied to
the string s to perform operations like changing case, replacing characters, splitting into a list,
and joining the elements of a list back into a string.

Program 2: Determining the Number of Times a Given Letter Occurs in a String

Question:
Write a Python program to determine the number of times a given letter occurs in a string.

Test Cases:

• Standard Case:

o Input: s = "banana", letter = "a"

▪ Expected Output: 3

o Input: s = "apple", letter = "p"

▪ Expected Output: 2

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 27

Solution Explanation:

• The program uses the built-in count() function of the string class to count how many times
the specified letter appears in the string.

Program 3: Checking if a String is a Palindrome or Not

Question:
Write a Python program to check if a string is a palindrome.

Test Cases:

• Standard Case:

o Input: s = "madam"

▪ Expected Output: madam is a palindrome

o Input: s = "hello"

▪ Expected Output: hello is not a palindrome

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 28

Solution Explanation:

• The program checks if the string is equal to its reverse (s[::-1]). If they are the same, the
string is a palindrome.

Program 4: Illustrating the in Operator and Counting Number of Lowercase Characters in a String

Question:
Illustrate the use of the in operator and write a Python program to count the number of lowercase
characters in a string.

Test Cases:

• Standard Case:

o Input: s = "Hello World"

▪ Expected Output:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 29

▪ Is 'Hello' in string? True

▪ Lowercase letters: 8

Solution Explanation:

• The in operator checks if a substring exists within a string. The count_lowercase function
counts how many characters in the string are lowercase using islower().

Program 5: Replacing All Occurrences of Letter ‘a’ with Letter ‘x’ in a String

Question:
Write a Python program to replace all occurrences of the letter ‘a’ with the letter ‘x’ in a string.

Test Cases:

• Standard Case:

o Input: s = "banana"

▪ Expected Output: bxnxbx

o Input: s = "apple"

▪ Expected Output: xpple

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 30

Solution Explanation:

• The program uses the replace() function to replace all occurrences of the letter 'a' with 'x' in
the string.

Additional Notes for Instructors:

• Solution Hints:

o Program 1 (String Functions): Introduce the importance of string functions like


split(), join(), find(), and replace(). Explain their use in real-world scenarios (e.g.,
processing input data).

o Program 2 (Counting Occurrences): Explain how the count() method is a powerful


built-in function to solve counting problems efficiently.

o Program 3 (Palindrome Check): Emphasize the simplicity of palindrome checking


using slicing and the importance of string manipulation in text processing.

o Program 4 (Lowercase Count): Discuss how string iteration with conditions can help
count specific types of characters (e.g., lowercase).

o Program 5 (Character Replacement): Explain how string mutation works in Python


and the utility of the replace() function for text processing tasks like censuring or
formatting.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 31

Week 7: Programs on Lists


1. Write a program to implement the following list functions a)len() b)extend() c)sort() d) append()
e)insert() f)remove()

2. Write a program to pass list as an argument to a function

3. Write a python program to find the largest and smallest number in a list.

4. Write a python program to merge two lists and sort it.

5. Write a python program to remove the duplicate items from a list. 6. Write a python program to
find sum of elements in a list

Objective:

In this week, students will practice working with lists, understanding common list operations, and
passing lists as arguments to functions. The goal is to familiarize students with list functions,
iteration, and list manipulation in Python.

Program 1: Implementing Common List Functions

Question:
Write a Python program to implement the following list functions:

• len()

• extend()

• sort()

• append()

• insert()

• remove()

Test Cases:

• Standard Case:

o Input: lst = [3, 1, 4, 1, 5, 9]

▪ Expected Output:

▪ Length of list: 6

▪ Extended list: [3, 1, 4, 1, 5, 9, 2, 6]

▪ Sorted list: [1, 1, 3, 4, 5, 9]

▪ List after append: [1, 1, 3, 4, 5, 9, 7]

▪ List after insert at position 2: [1, 1, 8, 3, 4, 5, 9]

▪ List after remove 5: [1, 1, 8, 3, 4, 9]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 32

Solution Explanation:

• The program demonstrates how to use various list methods like len(), extend(), sort(),
append(), insert(), and remove() to manipulate a list.

• len() returns the number of elements in the list.

• extend() adds all elements from another list.

• sort() sorts the list in ascending order.

• append() adds an element to the end of the list.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 33

• insert() inserts an element at a specified index.

• remove() removes the first occurrence of a given element.

Program 2: Passing List as an Argument to a Function

Question:
Write a Python program to pass a list as an argument to a function.

Test Cases:

• Standard Case:

o Input: lst = [10, 20, 30, 40, 50]

▪ Expected Output: Sum of elements in list: 150

Solution Explanation:

• This program demonstrates how to pass a list to a function. The function sum_of_list()
calculates the sum of all elements in the list using Python's built-in sum() function.

Program 3: Finding Largest and Smallest Number in a List

Question:
Write a Python program to find the largest and smallest number in a list.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 34

Test Cases:

• Standard Case:

o Input: lst = [10, 20, 4, 45, 99]

▪ Expected Output:

▪ Largest number: 99

▪ Smallest number: 4

Solution Explanation:

• The program uses Python's built-in max() and min() functions to find the largest and smallest
numbers in a list.

Program 4: Merging and Sorting Two Lists

Question:
Write a Python program to merge two lists and then sort the resulting list.

Test Cases:

• Standard Case:

o Input: lst1 = [1, 2, 3], lst2 = [4, 5, 6]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 35

▪ Expected Output: Merged and sorted list: [1, 2, 3, 4, 5, 6]

Solution Explanation:

• The program merges the two lists using the + operator and then sorts the resulting list using
the sort() method.

Program 5: Removing Duplicate Items from a List

Question:
Write a Python program to remove duplicate items from a list.

Test Cases:

• Standard Case:

o Input: lst = [1, 2, 2, 3, 4, 5, 5]

▪ Expected Output: List after removing duplicates: [1, 2, 3, 4, 5]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 36

Solution Explanation:

• The program converts the list to a set, which automatically removes duplicates since sets do
not allow duplicate elements. Then, it converts the set back to a list.

Program 6: Finding the Sum of Elements in a List

Question:
Write a Python program to find the sum of elements in a list.

Test Cases:

• Standard Case:

o Input: lst = [1, 2, 3, 4, 5]

▪ Expected Output: Sum of elements: 15

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 37

Solution Explanation:

• The program uses the built-in sum() function to calculate the sum of the elements in the list.

Additional Notes for Instructors:

• Solution Hints:

o Program 1 (List Functions): Discuss the importance of list operations like appending,
inserting, and removing elements. Also, explain how to sort lists and extend them
with other elements.

o Program 2 (Passing List to a Function): Explain how Python allows passing mutable
objects like lists to functions, which can then modify the original list if needed.

o Program 3 (Largest and Smallest Number): Explain how max() and min() work
efficiently to find extreme values in a list.

o Program 4 (Merging Lists): Discuss how merging lists works and the efficiency of
sorting a list after combining elements.

o Program 5 (Removing Duplicates): Explain the significance of using sets for


eliminating duplicates.

o Program 6 (Sum of List Elements): Highlight the use of sum() and its computational
efficiency when working with numeric lists.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 38

Week 8: Programs on Tuples and Dictionaries

1. Write a program to create a list of tuples with the first element as the number and the second
element as the square of the first element.

2. Write a python program that takes the list of tuples and sorts the list of tuples in increasing order
by the last element in each tuple.

3. Write a program to implement the following dictionary methods a) keys() b) values() c)items() d)
pop() e)delete()

4. Write a python program to add a key value pair to a dictionary and update the dictionary based on
the key.

5. Write a Program to do a reverse dictionary lookup in python

Objective:

In this week, students will work on operations related to tuples and dictionaries in Python. The goal
is to help students understand the basic concepts of tuples and dictionaries, as well as common
operations and methods that can be applied to them.

Program 1: Creating a List of Tuples with Numbers and Their Squares

Question:
Write a program to create a list of tuples where the first element is a number and the second
element is the square of the number.

Test Cases:

• Standard Case:

o Input: n = 5

▪ Expected Output: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 39

Solution Explanation:

• The function create_tuples() takes a number n and generates a list of tuples where the first
element is the number and the second element is the square of the number. The for loop
inside a list comprehension iterates through the numbers from 1 to n and creates a tuple
with each number and its square.

Program 2: Sorting a List of Tuples by the Last Element

Question:
Write a Python program that takes a list of tuples and sorts the list of tuples in increasing order
based on the last element of each tuple.

Test Cases:

• Standard Case:

o Input: [(1, 2), (3, 1), (2, 3)]

▪ Expected Output: [(3, 1), (1, 2), (2, 3)]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 40

Solution Explanation:

• The sort_by_last_element() function uses the sorted() function with a lambda function as
the key to sort the list of tuples by the second element (x[1]) of each tuple.

Program 3: Implementing Dictionary Methods

Question:
Write a program to implement the following dictionary methods:

• keys()

• values()

• items()

• pop()

• delete()

Test Cases:

• Standard Case:

o Input: d = {"a": 1, "b": 2, "c": 3}

▪ Expected Output:

▪ Keys: ['a', 'b', 'c']

▪ Values: [1, 2, 3]

▪ Items: [('a', 1), ('b', 2), ('c', 3)]

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 41

▪ Pop 'b': ('b', 2)

▪ Dictionary after pop: {'a': 1, 'c': 3}

Solution Explanation:

• This program demonstrates several dictionary methods:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 42

o keys(): Returns a list of all the keys in the dictionary.

o values(): Returns a list of all the values in the dictionary.

o items(): Returns a list of key-value pairs in the dictionary as tuples.

o pop(): Removes and returns the value associated with a specific key.

o del: Deletes a key-value pair from the dictionary by specifying the key.

Program 4: Adding and Updating Key-Value Pairs in a Dictionary

Question:
Write a Python program to add a key-value pair to a dictionary and update the dictionary based on
the key.

Test Cases:

• Standard Case:

o Input: d = {"a": 1, "b": 2}, new_key = "c", new_value = 3

▪ Expected Output: Dictionary after adding and updating: {'a': 1, 'b': 2, 'c': 3}

Solution Explanation:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 43

• The add_and_update() function simply assigns a new key-value pair to the dictionary. If the
key already exists, the function updates the value associated with that key.

Program 5: Reverse Dictionary Lookup

Question:
Write a program to do a reverse dictionary lookup in Python, i.e., given a value, find the
corresponding key.

Test Cases:

• Standard Case:

o Input: d = {"a": 1, "b": 2, "c": 3}, value = 2

▪ Expected Output: Key for value 2: b

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 44

Solution Explanation:

• The reverse_lookup() function iterates over the dictionary and checks if the given value
exists. If it does, the function returns the corresponding key. If not, it returns None.

Additional Notes for Instructors:

• Solution Hints:

o Program 1 (Creating Tuples): Explain the concept of tuples and how they are
immutable. Discuss how tuple elements can be computed (e.g., squaring the
number).

o Program 2 (Sorting Tuples): Discuss the importance of sorting and how sorting
tuples works when using the last element of the tuple.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 45

o Program 3 (Dictionary Methods): Discuss the fundamental methods of dictionaries


and their importance in manipulating key-value pairs. Also, explain the difference
between pop() and del in terms of usage.

o Program 4 (Adding and Updating Dictionary): Emphasize the flexibility of


dictionaries and how they allow for dynamic insertion and updates.

o Program 5 (Reverse Dictionary Lookup): Introduce the concept of reverse lookups in


dictionaries and the importance of iterating through the dictionary when looking for
keys based on values.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 46

Week 9: Programs on Files


1. Write a program to implement read(), readline(), readlines(), write(), writelines() methods on files.
2. Write a program to implement seek(), tell() and flush() methods with different arguments in a file.
3. Write a program to generate 20 random numbers in the range of 1 to 100 and write to a file.

Objective:

In this week, students will learn and work with different file handling operations in Python. The goal
is to help students understand how to read from and write to files, manipulate file pointers, and
work with file methods such as read(), readline(), write(), seek(), and flush().

Program 1: Implementing read(), readline(), readlines(), write(), and writelines() Methods

Question:
Write a program to demonstrate the following file handling methods:

• read()

• readline()

• readlines()

• write()

• writelines()

Test Cases:

• Test Case 1: Writing to a file and then reading it using read(), readline(), and readlines().

• Test Case 2: Writing multiple lines using writelines().

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 47

Solution Explanation:

• The program demonstrates the usage of write() to write multiple lines to a file.

• The read() method reads the entire content of the file, while readline() reads the file one line
at a time. readlines() reads all lines into a list.

• After each read operation, we use seek(0) to reset the file pointer to the beginning of the file
to allow re-reading.

Program 2: Implementing seek(), tell(), and flush() Methods

Question:
Write a program to demonstrate the seek(), tell(), and flush() methods in a file.

Test Cases:

• Test Case 1: Using seek() to change the file pointer's position and then using tell() to get the
current position.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 48

• Test Case 2: Writing data to a file and using flush() to flush the buffer.

Solution Explanation:

• The seek() method is used to move the file pointer to a specific position. In this case, we
move the pointer to the 6th byte.

• The tell() method returns the current position of the file pointer.

• The flush() method ensures that any buffered data is written to the file immediately.

Lab Manual - Week 9: Programs on Files

Lab Manual Objective:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 49

In this week, students will learn and work with different file handling operations in Python. The goal
is to help students understand how to read from and write to files, manipulate file pointers, and
work with file methods such as read(), readline(), write(), seek(), and flush().

Program 1: Implementing read(), readline(), readlines(), write(), and writelines() Methods

Question:
Write a program to demonstrate the following file handling methods:

• read()

• readline()

• readlines()

• write()

• writelines()

Test Cases:

• Test Case 1: Writing to a file and then reading it using read(), readline(), and readlines().

• Test Case 2: Writing multiple lines using writelines().

Program Solution:

python

Copy code

# File handling example demonstrating various methods

# Writing to a file using write() and writelines()

with open("[Link]", "w") as file:

[Link]("This is line 1.\n")

[Link]("This is line 2.\n")

[Link](["Line 3\n", "Line 4\n"])

# Reading from the file using read(), readline(), and readlines()

with open("[Link]", "r") as file:

print("Using read():")

print([Link]()) # Reads the entire content of the file

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 50

[Link](0) # Reset file pointer

print("Using readline():")

print([Link]()) # Reads the first line

[Link](0) # Reset file pointer

print("Using readlines():")

print([Link]()) # Reads all lines as a list

Solution Explanation:

• The program demonstrates the usage of write() to write multiple lines to a file.

• The read() method reads the entire content of the file, while readline() reads the file one line
at a time. readlines() reads all lines into a list.

• After each read operation, we use seek(0) to reset the file pointer to the beginning of the file
to allow re-reading.

Program 2: Implementing seek(), tell(), and flush() Methods

Question:
Write a program to demonstrate the seek(), tell(), and flush() methods in a file.

Test Cases:

• Test Case 1: Using seek() to change the file pointer's position and then using tell() to get the
current position.

• Test Case 2: Writing data to a file and using flush() to flush the buffer.

Program Solution:

python

Copy code

# Demonstrating seek(), tell(), and flush() methods

# Writing to a file

with open("[Link]", "w") as file:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 51

[Link]("Hello, World!\n")

[Link]("This is a test.\n")

# Using seek() and tell() methods

with open("[Link]", "r") as file:

print("Using tell():")

print([Link]()) # Shows the current position of the file pointer

[Link](6) # Move file pointer to the 6th byte

print("After seek(6), tell():")

print([Link]()) # New position of the file pointer

print("Using readline() after seek:")

print([Link]()) # Reads from the 6th byte

# Using flush() method

with open("[Link]", "w") as file:

[Link]("Flushing this content!")

[Link]() # Ensure the content is written to the file

print("Flush operation completed.")

Solution Explanation:

• The seek() method is used to move the file pointer to a specific position. In this case, we
move the pointer to the 6th byte.

• The tell() method returns the current position of the file pointer.

• The flush() method ensures that any buffered data is written to the file immediately.

Program 3: Generating 20 Random Numbers and Writing to a File

Question:
Write a Python program that generates 20 random numbers in the range of 1 to 100 and writes them
to a file.

Test Cases:

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 52

• Test Case 1: Generating 20 random numbers between 1 and 100 and writing them to a file.

• Test Case 2: Verifying the file content.

Solution Explanation:

• The program generates 20 random numbers using the [Link]() function and writes
each number to a file called random_numbers.txt.

• After writing, the file is opened again to read and verify the contents.

Additional Notes for Instructors:

• Program 1:

o Emphasize the differences between the read(), readline(), and readlines() methods,
and discuss when to use each based on the use case.

o Demonstrate the importance of file pointers and how operations like seek() and tell()
help manipulate them.

• Program 2:

o Explain that seek() moves the file pointer to a specified byte position, and tell()
reports the current byte position.

o Discuss flush() as a method to force write to the disk before closing the file, ensuring
no data is lost.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 53

• Program 3:

o Explain how random number generation works in Python using the random module.

o Discuss the importance of file I/O operations, particularly writing random data to a
file for logging or testing.

Week 10: Programs on Pandas Module


1. Write a program to import data from CSV to DataFrame in pandas.

2. Write a program to inspect data in DataFrame using head(), tail () and describe() functions in
pandas.

3. Write a program to perform sorting and slicing operations in pandas.

Objective:

In Week 10, students will explore the Pandas module, focusing on importing data, inspecting and
analyzing data in a DataFrame, and performing sorting and slicing operations. This will help them
handle real-world datasets effectively and manipulate data efficiently using Pandas.

Program 1: Importing Data from CSV to DataFrame in Pandas

Question:
Write a program to import data from a CSV file into a Pandas DataFrame.

Test Cases:

• Test Case 1: Importing a CSV file and displaying the first few rows using head().

• Test Case 2: Checking the structure of the DataFrame by printing the columns and the shape
of the DataFrame.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 54

Solution Explanation:

• pd.read_csv() is used to read a CSV file and load it into a DataFrame.

• head() displays the first 5 rows of the DataFrame (this is the default behavior, but you can
specify the number of rows).

• columns shows the column names, and shape gives the number of rows and columns in the
DataFrame.

Program 2: Inspecting Data in DataFrame Using head(), tail(), and describe() Functions

Question:
Write a program to inspect data in a DataFrame using the head(), tail(), and describe() functions in
Pandas.

Test Cases:

• Test Case 1: Display the first 10 rows using head().

• Test Case 2: Display the last 5 rows using tail().

• Test Case 3: Display descriptive statistics (mean, median, etc.) using describe().

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 55

Solution Explanation:

• head(10) returns the first 10 rows.

• tail() returns the last 5 rows by default, which can be changed by passing a number.

• describe() provides statistical summaries of numerical columns, including count, mean,


standard deviation, and other quartile statistics.

Program 3: Sorting and Slicing Operations in Pandas

Question:
Write a program to perform sorting and slicing operations in Pandas.

Test Cases:

• Test Case 1: Sort the DataFrame by a specific column (e.g., "Age").

• Test Case 2: Slice the DataFrame to display rows from index 10 to 20 and columns "Name"
and "Age".

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 56

Solution Explanation:

• sort_values(by='Age') sorts the DataFrame by the "Age" column. You can specify
ascending=False for descending order.

• loc[10:20, ['Name', 'Age']] slices the DataFrame to display rows from index 10 to 20 and
specific columns, like "Name" and "Age". Replace these column names based on your actual
dataset.

Additional Notes for Instructors:

• Program 1:

o Discuss how importing data from CSV files into a DataFrame is a crucial step in data
analysis. Ensure students understand the importance of setting the correct file path.

o Show the utility of head(), which helps to quickly glance at the dataset, and shape,
which tells about the dataset's dimensions.

• Program 2:

o The tail() method is useful to inspect the last rows of the dataset, especially when
dealing with large datasets.

o The describe() method is invaluable for obtaining an overview of numerical columns,


especially for identifying outliers and understanding data distributions.

• Program 3:

o Sorting is essential when preparing data for analysis, especially when dealing with
large datasets that need to be organized.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 57

o Slicing is useful for focusing on specific rows and columns, which is especially helpful
in exploratory data analysis (EDA) and when performing operations like filtering or
grouping data.

Week 11: Programs on GUI


1. Design and develop a GUI application to display ―Hello World.

2. Design and develop a GUI application using Label, Entry and Button widgets.

3. Design and develop a GUI application using Tkinter Geometry methods pack(), grid(), place().

4. Design and develop a GUI application using CheckButton and Radiobutton widgets.

Objective:

In Week 11, students will learn how to design and develop GUI (Graphical User Interface)
applications using the Tkinter module in Python. These applications will demonstrate the use of
various Tkinter widgets and layout methods such as labels, buttons, entry fields, and geometry
managers.

Program 1: Design and Develop a GUI Application to Display "Hello World"

Question:
Design and develop a simple GUI application that displays the message "Hello World" when the
application is launched.

Test Cases:

• Test Case 1: Verify if the "Hello World" message is displayed correctly on the window.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 58

Solution Explanation:

• [Link]() creates the main window.

• [Link]() creates a label widget to display the text "Hello World."

• The pack() method is used to display the label in the window.

• [Link]() runs the Tkinter event loop to display the window until it is closed by the
user.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 59

Program 2: Design and Develop a GUI Application Using Label, Entry, and Button Widgets

Question:
Design and develop a GUI application that contains a label, an entry field for user input, and a
button. When the button is clicked, the entered text is displayed in the label.

Test Cases:

• Test Case 1: Verify that the label displays the text entered in the entry field when the button
is clicked.

Solution Explanation:

• The entry widget allows the user to input text.

• The button widget triggers the update_label() function, which retrieves the text from the
entry widget and updates the label.

• [Link](text=entered_text) updates the label with the new text.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 60

Program 3: Design and Develop a GUI Application Using Tkinter Geometry Methods (pack(), grid(),
place())

Question:
Design and develop a GUI application that demonstrates the use of Tkinter geometry methods:
pack(), grid(), and place().

Test Cases:

• Test Case 1: Verify the layout of widgets when using pack().

• Test Case 2: Verify the layout of widgets when using grid().

• Test Case 3: Verify the layout of widgets when using place().

Solution Explanation:

• pack() automatically places widgets in the available space, stacking them vertically.

• grid(row, column) places widgets in a grid layout, allowing precise positioning in rows and
columns.

• place(x, y) places widgets at specific coordinates (x, y) on the window.

Program 4: Design and Develop a GUI Application Using Checkbutton and Radiobutton Widgets

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 61

Question:
Design and develop a GUI application that uses a Checkbutton and a Radiobutton. The check button
should allow the user to select multiple options, and the radio button should allow the user to select
only one option from a set of choices.

Test Cases:

• Test Case 1: Verify that multiple check buttons can be selected.

• Test Case 2: Verify that only one radio button can be selected at a time.

Solution Explanation:

• Checkbutton uses an IntVar() to track whether the box is checked or unchecked.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 62

• Radiobutton uses a StringVar() to store the selected value. Only one radio button can be
selected at a time from a group.

• When the button is clicked, the display_selection() function is triggered to show the selected
checkbutton and radiobutton values.

Additional Notes for Instructors:

• Program 1: The "Hello World" program demonstrates the basic structure of any Tkinter
application. It’s a simple example to introduce students to Tkinter.

• Program 2: Using Label, Entry, and Button widgets helps students understand how to interact
with the user and capture input, which is an essential part of GUI programming.

• Program 3: The use of different geometry managers (pack(), grid(), and place()) will help
students choose the appropriate layout method for their application.

• Program 4: The Checkbutton and Radiobutton widgets are fundamental for creating forms
where users select multiple or single options, respectively.

Week 12: Programs on GUI (Continued)


1. Design and develop a GUI application using Menu and Menubutton widgets.

2. Design and develop a GUI application using Listbox and Scrollbar widgets.

3. Design and develop a GUI application using Messagebox and File Dialog widget

Objective:

In Week 12, students will continue their exploration of GUI (Graphical User Interface) development
using Tkinter. This week’s focus will be on advanced Tkinter widgets such as Menu, Menubutton,
Listbox, Scrollbar, Messagebox, and File Dialog.

Program 1: Design and Develop a GUI Application Using Menu and Menubutton Widgets

Question:
Design and develop a GUI application that includes a menu bar with a few options and a menubutton
that allows the user to select different options.

Test Cases:

• Test Case 1: Verify that the menu options work and perform the intended actions when
clicked.

• Test Case 2: Verify that the Menubutton dropdown appears when clicked.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 63

Solution Explanation:

• The Menu widget creates a menu bar, and add_command() is used to add items to the
menu.

• The Menubutton widget creates a button with a dropdown list, and we define the options
inside the dropdown menu.

• [Link]() is used to display messages when a menu or menubutton option is


selected.

Program 2: Design and Develop a GUI Application Using Listbox and Scrollbar Widgets

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 64

Question:
Design and develop a GUI application that uses a Listbox to display a list of items and a Scrollbar to
allow scrolling through the list if it exceeds the visible area.

Test Cases:

• Test Case 1: Verify that the listbox displays the items correctly.

• Test Case 2: Verify that the scrollbar works when the list is too long to fit in the listbox.

Solution Explanation:

• The Listbox widget displays a list of items, and Scrollbar allows the listbox to be scrollable.

• yscrollcommand is used to link the scrollbar to the listbox, and command=[Link]


updates the scrollbar’s position when the listbox is scrolled.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 65

Program 3: Design and Develop a GUI Application Using Messagebox and File Dialog Widgets

Question:
Design and develop a GUI application that uses a Messagebox to display a message and a File Dialog
widget to allow the user to open a file using a file explorer dialog.

Test Cases:

• Test Case 1: Verify that the messagebox displays the correct message.

• Test Case 2: Verify that the file dialog allows the user to open a file and display its path.

Solution Explanation:

• The [Link]() method displays an informational message box with a custom


message.

• The [Link]() method opens a file dialog to allow the user to select and
open a file. The selected file path is shown using a messagebox.

ECE Department Python Programming Lab MVGR College of Engineering (A)


Page 66

Additional Notes for Instructors:

• Program 1: The Menu and Menubutton widgets demonstrate how to create simple menus
and drop-down buttons in a GUI, which are common elements in desktop applications.

• Program 2: Using the Listbox and Scrollbar widgets teaches students how to display lists of
items with the ability to scroll through long lists, a feature often seen in applications like file
explorers or contact lists.

• Program 3: The Messagebox and File Dialog widgets are essential for interactive applications,
providing users with feedback and enabling file selection functionality.

ECE Department Python Programming Lab MVGR College of Engineering (A)

You might also like