0% found this document useful (0 votes)
5 views44 pages

Python Lab Manual Updated

The document outlines various Python programming exercises focusing on different concepts such as variable types, conditional statements, loops, and functions. Each exercise includes an aim, procedure, execution code, sample output, and assessment questions. The exercises aim to enhance understanding of basic Python programming skills through practical applications.

Uploaded by

forgpt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Python Lab Manual Updated

The document outlines various Python programming exercises focusing on different concepts such as variable types, conditional statements, loops, and functions. Each exercise includes an aim, procedure, execution code, sample output, and assessment questions. The exercises aim to enhance understanding of basic Python programming skills through practical applications.

Uploaded by

forgpt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Ex.

No: 1
Variables of Different Data Types and Basic Operations in Python
Date:

AIM
To create variables of different data types such as integer, float, and string, and perform basic
operations like addition, subtraction, and concatenation.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Declare variables of different data types such as integer, float, and string.
4. Assign suitable values to the variables.
5. Perform addition using integer variables.
6. Perform subtraction using float variables.
7. Perform concatenation using string variables.
8. Use the print() function to display the results on the screen.
9. Save the program with the file name variables_operations.py.
10. Run the program by pressing F5 or selecting Run → Run Module.
11. Verify the output displayed and check whether the operations are performed correctly.

EXECUTION:
# Creating variables of different data types
# Integer variable
num1 = 10
num2 = 5

# Float variable
decimal1 = 12.5
decimal2 = 7.5

# String variable
str1 = "Hello"
str2 = "World"

# Addition of integers
addition = num1 + num2

# Subtraction of floats
subtraction = decimal1 - decimal2

# String concatenation
concatenation = str1 + " " + str2

# Displaying the results


print("Addition of integers:", addition)
print("Subtraction of floats:", subtraction)
print("Concatenation of strings:", concatenation)
SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No: 1 Variables of Different Data Types and Basic Operations in Python

Worksheet No : 1
1 Which data type is used to store whole numbers in Python?
a) float b) string c) int d) bool
2 Which data type is used to store decimal numbers?
a) int b) float c) string d) list
3 Which of the following is a valid variable name in Python?
a) 1value b) value_1 c) value-1 d) value 1
4 What will be the output of: print(type(10))?
a) float b) int c) str d) bool
5 Which data type is used to store text in Python?
a) int b) float c) string d) bool
6 What is the output of 10 + 5?
a) 15 b) 105 c) 5 d) 50
7 Which function is used to get the data type of a variable?
a) datatype() b) type() c) check() d) var()
8 The ________ function is used to display output in Python.
9 The result of "Hello" + "World" is ________.
10 25.6 is an example of ________ data type.
11 Strings in Python are written inside ________.
12 Which of the following is a valid variable name?
a) 1num b) num_1 c) num-1 d) class
13 Which keyword is used to take input from the user?
a) print b) input c) read d) scan
14 What is the output of print("Python")?
a) Error b) Python c) "Python" d) None
15 10 is an example of ________ data type.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:
APPLICATIONS
2. A student wants to store his roll number, marks, and name in Python. Write a program
to create suitable variables and display them.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Marks (5+3+2) /10
Semester
Signature of Signature of the
the student facilitator with
date
Ex. No: 2
Even or Odd Number using Conditional Statements in Python
Date:

AIM
To write a Python program that checks whether a given number is even or odd using
conditional statements (if-else).

PROCEDURE
1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Write the program to accept a number from the user using the input() function.
4. Convert the input value into integer using int().
5. Use the modulus operator % to divide the number by 2 and check the remainder.
6. Apply the if-else conditional statement:
 If the remainder is 0, the number is even.
 Otherwise, the number is odd.
7. Use the print() function to display the result.
8. Save the program with the file name even_odd.py.
9. Run the program by pressing F5 or selecting Run → Run Module.
10. Observe the output displayed on the screen.

EXECUTION:
# Program to check whether a number is even or odd

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

if num % 2 == 0:
print("The number is Even")
else:
print("The number is Odd")

SAMPLE OUTPUT:

RESULT:
Thus, the above task was executed and the output was successfully verified.
Ex. No: 2 Even or Odd Number using Conditional Statements in Python

Worksheet No : 2
1 Which statement is used for decision making in Python?
a) for b) if c) print d) input
2 The ________ operator is used to find the remainder.
a) + b) / c) % d) *
3 Which symbol is used for equality checking in Python?
a) = b) == c) != d) >=
4 Conditional statements help in making ________.
a) loops b) decisions c) strings d) variables
5 The condition num % 2 == 0 checks whether the number is ________.
a) odd b) prime c) even d) negative
6 Which data type is used with int()?
a) Integer b) String c) Float d) List
7 What is the result of 9 % 2?
a) 0 b) 1 c) 2 d) 9
8 The ________ keyword is used when the condition is false.
9 Which function is used to display output?
a) input() b) print() c) scan() d) read()
10 What does num % 2 == 0 check?
11 The ________ block executes when the condition is true.
12 Python uses indentation to define a ________.
a) block of code b) variable c) operator d) value
13 The word else is used without any ________.
a) value b) condition c) number d) operator
14 Which statement is used for decision making in Python?
a) loop b) if c) def d) class
15 In Python, indentation is used to define a __________.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. A teacher wants to check whether a student’s roll number is even or odd for classroom
arrangement. Write a Python program using if-else to determine this.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Marks (5+3+2) /10
Semester
Signature of Signature of the
the student facilitator with
date
Ex. No:3
Multiplication Table Using for Loop in Python
Date:

AIM
To write a Python program that prints the multiplication table for a given number using a
for loop.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Write the program to accept a number from the user using the input() function.
4. Convert the input value into integer using int().
5. Use the for loop with range(1, 11) to repeat the process from 1 to 10.
6. Inside the loop, multiply the given number by the loop variable.
7. Use the print() function to display the multiplication table.
8. Save the program with the file name multiplication_table.py.
9. Run the program by pressing F5 or selecting Run → Run Module.
[Link] the output displayed on the screen.

EXECUTION:
# Program to print multiplication table using for loop

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

for i in range(1, 11):


print(num, "x", i, "=", num * i)

SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No: 3 Multiplication Table Using for Loop in Python

Worksheet No : 3
1 Which loop is commonly used to print a multiplication table in Python?
a) while b) for c) if d) else
2 Which function is used to generate a sequence in a for loop?
a) input() b) print() c) range() d) len()
3 What is the starting value in range(1, 11)?
a) 0 b) 1 c) 10 d) 11
4 In for i in range(1, 11):, i is called ________.
a) function b) loop variable c) operator d) keyword
5 The condition num % 2 == 0 checks whether the number is ________.
a) odd b) prime c) even d) negative
6 The for loop is used for ________ execution.
a) single b) repeated c) conditional d) random
7 In for i in range(1, 11):, what is i?
a) function b) constant c) loop variable d) operator
8 The for loop repeats a block of code for a fixed number of ________.
9 The range(1, 11) function generates numbers from 1 to __________.
10 Which keyword starts a loop in Python?
a) if b) for c) else d) print
11 The print() function is used to ________ the table.
12 Which function is used to display output?
a) numbers() b) list() c ) range() d) count()
13 for i in range() uses ________ to control repetition.
a) loop variable b) string c) condition d) function
14 What is the ending value printed using range(1, 11)?
a) 9 b) 10 c) 11 d) 12
15 In for i in range(1, 11):, the loop runs __________ times.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. A fruit seller wants to calculate the total price for buying 1 to 10 kg of apples when the price per
kg is given. Write a Python program using a for loop to display the multiplication table.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:4
Factorial of a Number Using Function in Python
Date:

AIM
To write a Python program that creates a function to calculate the factorial of a number
and test the function with different input values.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Define a function named factorial() to calculate the factorial of a number.
4. Initialize the factorial value as 1.
5. Use a for loop to multiply all numbers from 1 to the given number.
6. Return the factorial value from the function using the return statement.
7. Accept a number from the user using the input() function.
8. Convert the input into integer using int().
9. Call the factorial() function and store the result.
10. Display the factorial using the print() function.
11. Save the program with the file name factorial_function.py.
12. Run the program by pressing F5 or selecting Run → Run Module.
13. Observe the output displayed on the screen.

EXECUTION:
# Program to find factorial of a number using function
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
num = int(input("Enter a number: "))
result = factorial(num)
print("Factorial of", num, "is", result)

SAMPLE OUTPUT:

RESULT:
Thus, the above task was executed and the output was successfully verified.
Ex. No: 4 Factorial of a Number Using Function in Python

Worksheet No : 4
1 Which statement is used to send a value back from a function?
a) break b) return c) print d) input
2 The factorial of 0 is ________.
a) 0 b) 1 c) undefined d) 10
3 Which keyword is used to define a function in Python?
a) function b) def c) fun d) define
4 Which keyword is used to define a function in Python?
a) function b) define c) def d) fun
5 The keyword used to define a function is __________.
6 Which loop is commonly used to find factorial inside a function?
a) for b) while c) both a and b d) none
7 What is the factorial formula?
a) n + (n-1) b) n * (n-1) * ... * 1 c) n - (n-1) d) n / (n-1)
8 The expression n + 1 in range(1, n + 1) is used to include ________.
a) 0 b) last number c) first number d) negative values
9 In a loop-based factorial, the initial value of the result is usually set to __________.
10 Which loop is commonly used to find factorial inside a function?
a) for b) while c) both a and b d) none
11 A function helps to avoid repeated writing of the same ________.
a) variable b) code c) number d) string
12 In factorial calculation, the initial value of fact is usually ________.
13 The statement fact = fact * i is used for ________.
a) addition b) multiplication c) division d) comparison
14 The expression n * fact(n-1) is used in __________ approach.
a) Iterative b) Recursive c) Logical d) Sequential
15 In a factorial function, the parameter represents the __________.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. Explain how recursion is used to calculate the factorial of a number in Python.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:5
List and Tuple Operations in Python
Date:

AIM
To write a Python program to explore lists and tuples by performing operations like
sorting, appending, and slicing on a list of numbers.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Create a list of numbers and store some integer values in it.
4. Display the original list using the print() function.
5. Use the append() method to add a new element to the list.
6. Use the sort() method to arrange the list elements in ascending order.
7. Use slicing operation to display only a selected part of the list.
8. Create a tuple with sample values and display it.
9. Use the print() function to show all results on the screen.
10. Save the program with the file name list_tuple_operations.py.
11. Run the program by pressing F5 or selecting Run → Run Module.
12. Observe the output displayed on the screen.

EXECUTION:
# Program to perform list operations

# Creating a list of numbers


numbers = [15, 8, 23, 4, 10]
print("Original List:", numbers)

# Appending a new number


[Link](18)
print("After Appending:", numbers)

# Sorting the list


[Link]()
print("After Sorting:", numbers)

# Slicing the list


print("Sliced List (first 3 elements):", numbers[:3])

# Creating a tuple
sample_tuple = (1, 2, 3, 4, 5)
print("Tuple:", sample_tuple)

SAMPLE OUTPUT:
RESULT:
Thus, the above task was executed and the output was successfully verified.

Ex. No: 5 List and Tuple Operations in Python


Worksheet No : 5
1 Which method is used to remove the last element from a list in Python?
a) delete() b) remove() c) pop() d) clear()
2 Which method is used to count the number of times an element appears in a
list? a) count() b) total() c) find() d) sum()
3 Which method is used to find the position of an element in a list?
a) search() b) index() c) locate() d) append()
4 What is the index value of the first element in a Python list?
a) 1 b) -1 c) 0 d) 2
5 Which operator is used to repeat list elements?
a) + b) - c) * d) /
6 What is the output of [2, 4] * 2?
a) [2, 4, 2, 4] b) [4, 8] c) [2, 2, 4, 4] d) Error
7 Which method is used to remove all elements from a list?
a) delete() b) clear() c) pop() d) erase()
8 What is the output of len([10, 20, 30])?
a) 2 b) 3 c) 30 d) Error
9 Negative indexing in Python starts from ________.
10 Which method is used to insert an element at a specific position in a list?
a) append() b) add() c) insert() d) push()
11 What will len([1,2,3]) return? a) 2 b) 1 c) 4 d) 3
12 Tuples are faster than lists because they are ________.
13 Which list method is used to reverse the order of elements?
a) reverse() b) sort() c) invert() d) flip()
14 Which keyword is used to check whether an element exists in a list?
a) in b) on c) at d) is
15 Which slicing expression gives the last two elements of a list a = [10, 20, 30, 40]?
a) a[:2] b) a[2:] c) a[1:3] d) a[-1]
PART – C INFERENCE AND APPLICATIONS
INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. A mobile shop owner wants to store the prices of different mobile phones in a list and add a new
mobile price to the list. Write a Python program using the append() method.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date

Ex. No:6
Dictionary Operations in Python
Date:

AIM
To write a Python program that uses a dictionary to store information about students
such as name, age, and grade, and perform operations like adding, updating, and accessing
dictionary elements.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Create a dictionary to store student details like name, age, and grade.
4. Display the original dictionary using the print() function.
5. Add a new key-value pair such as city using dictionary syntax.
6. Update an existing value such as grade using the key name.
7. Access specific elements like name and grade using their keys.
8. Display all results using the print() function.
9. Save the program with the file name dictionary_operations.py.
10. Run the program by pressing F5 or selecting Run → Run Module.
11. Observe the output displayed on the screen.

EXECUTION:
# Program to perform dictionary operations
# Creating a dictionary
student = {
"name": "Arun",
"age": 18,
"grade": "A"
}

print("Original Dictionary:", student)

# Adding a new element


student["city"] = "Chennai"
print("After Adding:", student)

# Updating an existing element


student["grade"] = "A+"
print("After Updating:", student)

# Accessing dictionary elements


print("Student Name:", student["name"])
print("Student Grade:", student["grade"])

SAMPLE OUTPUT:
RESULT:
Thus, the above task was executed and the output was successfully verified.

Ex. No: 6 Dictionary Operations in Python

Worksheet No : 6
1 Which data structure stores data in key-value pairs in Python?
a) list b) tuple c) dictionary d) string
2 Which symbol is used to create a dictionary in Python?
a) [] b) () c) {} d) <>
3 In a dictionary, each value is accessed using a ________.
a) index b) key c) loop d) operator
4 Which of the following is a valid dictionary example?
a) [1, 2, 3] b) (1, 2, 3) c) {"name": "Arun"} d) "Python"
5 Which method is used to get all keys in a dictionary?
a) keys() b) values() c) items() d) get()
6 Which method is used to get all values in a dictionary?
a) keys() b) values() c) items() d) update()
7 Which method is used to get both keys and values together?
a) keys() b) values() c) items() d) clear()
8 How do you add a new element to a dictionary?
a) append() b) insert() c) using a new key d) push()
9 Dictionary is a ________ data type in Python.
10 What will {"a":1}["a"] return?
a) a b) 1 c) error d) None
11 What is the output type of [Link]()?
a) list b) tuple c) dict_keys d) string
12 Dictionary elements are separated by ________.
13 A dictionary value can be of ________ data type.
a) only string b) only integer c) any d) only float
14 Dictionaries are mainly used for storing ________.
15 Which method removes the last inserted key-value pair in Python dictionary?
a) pop() b) popitem() c) clear() d) remove()
PART – C INFERENCE AND APPLICATIONS
INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. A hospital receptionist wants to store patient details such as name, age, and blood group in a
dictionary and display the patient’s blood group separately. Write a Python program for this.
Ans:

ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:7
Exception Handling in Python
Date:

AIM
To write a Python program that handles exceptions gracefully by taking user input for
division and managing the case where the user attempts to divide by zero.

PROCEDURE

1. Start the computer and open Python IDLE or any Python programming software.
2. Create a new Python file by selecting File → New File.
3. Write the program to accept two numbers from the user using the input()
function.
4. Convert the input values into integers using int().
5. Use the try block to perform the division operation.
6. Use the except ZeroDivisionError block to handle division by zero.
7. Use the except ValueError block to handle invalid input such as letters instead
of numbers.
8. Use the print() function to display the result or error message.
9. Save the program with the file name exception_handling.py.
[Link] the program by pressing F5 or selecting Run → Run Module.
[Link] the output displayed on the screen.

EXECUTION:
# Program for exception handling in division
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result =", result)

except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numbers.")

SAMPLE OUTPUT:

RESULT:
Thus, the above task was executed and the output was successfully verified.
Ex. No:7 Exception Handling in Python

Worksheet No : 7
1 Which keyword is used to handle exceptions in Python?
a) if b) try c) for d) while
2 Which block is used to catch an exception?
a) else b) except c) finally d) break
3 Which error occurs when dividing a number by zero?
a) ValueError b) NameError c) ZeroDivisionError d) TypeError
4 Which error occurs when invalid input like letters is entered instead of numbers?
a) ValueError b) IndexError c) KeyError d) ImportError
5 Which keyword is used to handle exceptions in Python?
a) catch b) try c) error d) except
6 The ________ block is used to test risky code in Python.
a) if b) try c) for d) while
7 Exception handling in Python uses the __________ block.
8 The result of 10 / 2 is ________.
a) 2 b) 5.0 c) 10 d) 20
9 Division by zero causes __________ error.
10 The ________ block always executes whether an exception occurs or not.
a) if b) else c) finally d) for
11 Exception handling helps to prevent program ________.
a) running b) crashing c) printing d) looping
12 Which keyword is used with try to handle specific errors?
a) except b) catch c) handle d) error
13 Exception handling is used to prevent program __________.
a) output b) crash c) input d) loop
14 A built-in error is called an __________.
15 except ValueError handles ________ input values.
a) valid b) invalid c) repeated d) fixed
PART – C INFERENCE AND APPLICATIONS
INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. A bus manager wants to divide total passengers by number of buses. If buses = 0, handle the
exception. Write a Python program.
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:8
Class Representing A Car
Date:

AIM
To design and implement a simple class representing a car using object-oriented
programming concepts, including attributes like make and model, and methods like start_engine()
and stop_engine().

PROCEDURE

1. Define a class named Car.


2. Create attributes such as make, model, and engine_status.
3. Initialize attributes using a constructor (__init__ method).
4. Define methods:
start_engine() → to start the car engine.
stop_engine() → to stop the car engine.
5. Create an object of the class.
6. Call the methods using the object.
7. Display output to verify functionality.

EXECUTION:
class Car:
def __init__(self, make, model):
[Link] = make
[Link] = model
self.engine_status = "Stopped"

def start_engine(self):
if self.engine_status == "Running":
print("Engine is already running.")
else:
self.engine_status = "Running"
print("Engine started.")

def stop_engine(self):
if self.engine_status == "Stopped":
print("Engine is already stopped.")
else:
self.engine_status = "Stopped"
print("Engine stopped.")

# Creating object
car1 = Car("Toyota", "Innova")

# Accessing methods
print("Car Make:", [Link])
print("Car Model:", [Link])
car1.start_engine()
car1.start_engine()
car1.stop_engine()
car1.stop_engine()

SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No:8 Class Representing A Car

Worksheet No : 8
1 What is a class in Python?
a) function b) blueprint for objects c) variable d) loop
2 Which keyword is used to define a class?
a) define b) class c) struct d) def
3 Which method initializes object attributes?
a) start() b) init() c) init() d) object()
4 What is an object?
a) function b) instance of class c) loop d) file
5 Which is an attribute of Car class?
a) start_engine b) make c) stop_engine d) run
6 What does start_engine() do?
a) stops engine b) deletes object c) starts engine d) pauses program
7 A class is a ______ for objects.
8 Which of the following is a mutable data type?
a) tuple b) str c) list d) int
9 A loop that runs a fixed number of times is ________ loop.
10 Which method is called automatically when object is created?
a) start() b) init() c) stop() d) main()
11 What is stored in attributes?
a) logic b) data c) errors d) loops
12 True or False values are stored in ________ data type.
13 Which of the following is OOP concept?
a) loop b) function c) class d) array
14 A ________ is a mutable data type in Python.
15 Default engine status is ______
a) running b) stopped c) active d) moving
PART – C INFERENCE AND APPLICATIONS
INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. What is the use of start_engine() method in real life simulation?
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:9
Basic GUI Application Using Tkinter
Date:

AIM
To design and implement a basic GUI (Graphical User Interface) application using
Tkinter in Python with entry fields and buttons.

PROCEDURE

1. Import the Tkinter library.


2. Create the main application window using Tk().
3. Add labels to display field names.
4. Add entry fields using Entry() for user input.
5. Create a button using Button() widget.
6. Define a function to handle button click event.
7. Display the entered data when button is clicked.
8. Run the main event loop using mainloop().

EXECUTION:
import tkinter as tk

def submit_data():
name = entry_name.get()
age = entry_age.get()
result_label.config(text="Name: " + name + " | Age: " + age)
# Create main window
window = [Link]()
[Link]("Simple GUI Form")
[Link]("300x200")
# Name label and entry
[Link](window, text="Name").pack()
entry_name = [Link](window)
entry_name.pack()
# Age label and entry
[Link](window, text="Age").pack()
entry_age = [Link](window)
entry_age.pack()
# Submit button
[Link](window, text="Submit", command=submit_data).pack()
# Result display label
result_label = [Link](window, text="")
result_label.pack()
# Run application
[Link]()
SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No:9 Basic GUI Application Using Tkinter

Worksheet No : 9
1 Which library is used to create GUI in Python?
a) math b) tkinter c) os d) random
2 Which function is used to create main window in Tkinter?
a) Window() b) Tk() c) Main() d) Gui()
3 Which widget is used for text input?
a) Label b) Button c) Entry d) Textbox
4 Which widget is used to display text?
a) Label b) Entry c) Button d) Frame
5 Which method is used to run Tkinter application?
a) start() b) run() c) mainloop() d) execute()
6 Which widget is used to perform action?
a) Label b) Button c) Entry d) Canvas
7 Tkinter is used to create ______ applications.
8 Which method is used to get value from Entry? a) set() b) get() c) read() d)
fetch()
9 The widget used for user input is ______.
10 Which function is used to create a button click action?
a) command b) action c) click d) event
11 What does GUI stand for? a) Graphical User Interface b) General User Input
c) Graphic Utility Interface d) Global User Interaction
12 The method used to run GUI program is ______.
13 What is Tkinter? a) database b) GUI library c) compiler d) IDE
14 The function used to create main window is ______.
15 A button performs an ______ when clicked.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. How is Label() useful in GUI applications?
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:10
Sorting Using sorted() Function and Lambda Function
Date:

AIM
To implement a sorting program using the sorted() function and a lambda function
to sort a list of tuples based on a specific element.

PROCEDURE

1. Create a list of tuples containing student details such as name and marks.
2. Use the sorted() function to sort the list.
3. Apply a lambda function as the key for sorting.
4. Specify the tuple element index to sort by marks.
5. Display the original list and the sorted list.
6. Verify the output.

EXECUTION:
# List of tuples (Name, Marks)
students = [
("Arun", 85),
("Bala", 92),
("Cathy", 78),
("David", 88)
]
# Sorting using sorted() and lambda
sorted_students = sorted(students, key=lambda x: x[1])
# Display output
print("Original List:")
print(students)

print("\nSorted List by Marks:")


print(sorted_students)

SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No:10 Basic GUI Application Using Tkinter

Worksheet No : 10
1 What does the sorted() function do?
a) deletes list b) sorts elements c) creates tuple d) stops program
2 What is a lambda function?
a) named function b) anonymous function c) loop d) class
3 Which keyword is used for lambda function?
a) function b) lambda c) def d) key
4 What type of data is used in this program?
a) list of tuples b) dictionary c) set d) string
5 sort([3,1,2]) returns ______. a) [3,2,1] b) [1,2,3] c) (1,2,3) d) {1,2,3}
6 What is the output type of sort()?
a) string b) tuple c) list d) integer
7 Which symbol is used to separate tuple values? a) ; b) : c) , d) .
8 Which bracket is used for a tuple? a) [ ] b) { } c) ( ) d) < >
9 The input given to sorted() must be ________.
10 Which argument is used for descending order in sorted()?
a) reverse=True b) desc=True c) order=False d) sort=False
11 sort() can be used on ________ and strings.
12 The output of sort([3,1,2]) is ________.
13 Lambda function is mainly used for:
a) simple short operations b) large programs c) file handling d) graphics
14 In x[1], index 1 refers to the ______ element.
15 The ______ function is used to arrange elements in order.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. Why is key=lambda x: x[1] used in the program?
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:11
Web Scraping using Beautifulsoup
Date:

AIM
To use the BeautifulSoup library in Python to scrape data from a website and
extract headlines from a news webpage.

PROCEDURE

1. Import necessary libraries (requests, BeautifulSoup)


2. Choose a news website (e.g., BBC News)
3. Send an HTTP request to fetch webpage content
4. Parse the HTML content using BeautifulSoup
5. Inspect webpage structure to find headline tags (like <h2>, <h3>)
6. Extract the text from these tags
7. Print the headlines
Requirements

 Python installed (3.x)


 Libraries:
o requests
o beautifulsoup4

Install required libraries using:

Command Line : pip install requests beautifulsoup4


EXECUTION:
import requests
from bs4 import BeautifulSoup

# URL of the news website


url = "[Link]

# Send HTTP request


response = [Link](url)

# Check if request was successful


if response.status_code == 200:
# Parse HTML content
soup = BeautifulSoup([Link], "[Link]")
# Find all headline tags (example: h2 tags)
headlines = soup.find_all("h2")
print("Top Headlines:\n")
# Loop through and print headlines
for i, headline in enumerate(headlines[:10]): # limiting to 10
print(f"{i+1}. {headline.get_text(strip=True)}")
else:
print("Failed to retrieve the webpage")
SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No:11 Basic GUI Application Using Tkinter

Worksheet No : 11
1 __________ is used to send HTTP requests in Python.
a) NumPy b) Requests c) Pandas d) Matplotlib
2 BeautifulSoup is used for __________ HTML content.
a) compiling b) parsing c) executing d) encrypting
3 The method used to fetch webpage content is __________.
a) get() b) post() c) fetch() d) retrieve()
4 The standard parser used in BeautifulSoup is __________.
a) [Link] b) [Link] c) [Link] d) [Link]
5 The HTTP success status code is __________.
6 __________ method is used to find multiple elements.
7 The function used to extract text from HTML tags is __________.
a) get_text() b) extract() c) read() d) parse()
8 The library used for web scraping in this experiment is __________.
a) TensorFlow b) BeautifulSoup c) Keras d) OpenCV
9 The response content is accessed using __________.
a) [Link] b) [Link] c) [Link] d) [Link]
10 The URL of the webpage is stored in a __________.
11 The loop used to iterate headlines is __________.
a) while b) do-while c) for d) switch
12 The method used to remove extra spaces is __________.
a) trim() b) strip() c) clean() d) remove()
13 The function enumerate() is used to get __________.
14 The file extension for Python programs is __________.
a) .java b) .py c) .cpp d) .html
15 Web scraping is used to __________ data from websites.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. How do you check whether a webpage request was successful? Write the condition.
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date
Ex. No:12
Data Visualization Using Matplotlib
Date:

AIM
To create a simple line chart and bar chart using the Matplotlib library and
customize their appearance.

PROCEDURE

1. Install the required library Matplotlib using the command pip install matplotlib in the terminal or
command prompt.
2. Open a Python editor or IDE and import the necessary module using import [Link] as
plt.
3. Prepare the sample data by defining two lists for X-axis and Y-axis values.
4. Create a figure using [Link]() and set the size of the plotting area to display multiple charts
clearly.
5. Use the subplot() function to divide the figure into sections for displaying more than one graph
in a single window.
6. In the first subplot, plot a line chart using [Link]() and customize it by adding color, markers,
line style, title, axis labels, and grid.
7. In the second subplot, plot a bar chart using [Link]() and customize it by adding color, title, and
axis labels.
8. Adjust the spacing between the plots using plt.tight_layout() to avoid overlapping.
9. Display both charts together using [Link]().
10. Save the program with a .py extension and execute it using the Python interpreter.
11. Observe the output window showing both the line chart and bar chart with proper
customization.

EXECUTION:
import [Link] as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
# Create a figure
[Link](figsize=(10, 5))
# ---------- Line Chart ----------
[Link](1, 2, 1) # 1 row, 2 columns, position 1
[Link](x, y, color='blue', marker='o', linestyle='--', linewidth=2)
[Link]("Line Chart")
[Link]("X-axis")
[Link]("Values")
[Link](True)
# ---------- Bar Chart ----------
[Link](1, 2, 2) # position 2
[Link](x, y, color='orange')
[Link]("Bar Chart")
[Link]("X-axis")
[Link]("Values")
# Adjust layout
plt.tight_layout()
# Display both plots
[Link]()

SAMPLE OUTPUT:

RESULT:

Thus, the above task was executed and the output was successfully verified.
Ex. No:12 Data Visualization Using Matplotlib

Worksheet No : 12
1 Matplotlib is used for __________.
a) Data visualization b) Web scraping c) Database d) Networking
2 The module used to import Matplotlib is __________.
a) plt b) mat c) pyplot d) graph
3 The function used to display plots is __________.
a) show() b) showplot() c) display() d) plotshow()
4 Bar chart is created using __________ function.
a) bar() b) bars() c) column() d) rect()
5 The function used to create figure window is __________.
6 The extension of Python file is __________.
7 Matplotlib is a __________ library.
a) database b) visualization c) AI d) networking
8 tight_layout() is used to avoid __________.
a) errors b) overlap c) plot creation d) deletion
9 The default alias for pyplot is __________.
10 Marker in line chart is used to show __________.
11 The default shape of bar chart is __________.
a) circles b) lines c) rectangles d) squares
12 The command used to install Matplotlib is __________.
13 The function used to add markers in a line chart is __________.
a) marker() b) mark() c) plot(marker='o') d) dot()
14 The parameter used to change bar color is __________.
a) shade b) color c) paint d) style
15 The library used to import pyplot is __________.

PART – C INFERENCE AND APPLICATIONS


INFERENCE
1. What have you inferred from this experiment?
Ans:

APPLICATIONS
2. How will you create a bar chart for given X and Y values in Matplotlib?
Ans:
ASSESSMENT
Name of the Name of
Student the
Facilitator
Register Comments :
Number
Year/ Semester Marks (5+3+2) /10

Signature of the Signature of the


student facilitator with
date

You might also like