lucky word file python
lucky word file python
SESSION : 24-25
PRACTICAL FILE
10 Practical No. 10: Create set, Access Set, Update Set, Delete Set.
1. Create a Dictionary
2. Access Dictionary
3. Update Dictionary
4. Delete Dictionary
Practical No. 14
14
Write a user Define Function to Implement for following Problem: Function
Positional/Required Argument, Function with keyword argument, Function
with default argument, Function with variable length argument
Practical No. 16: Write a python program to create and use a user defined
16 module for a given problem
Practical No. 17: Write a python program to demonstrate the use of
17 following module: 1. Math module 2. Random module 3. OS module
Practical No. 18: Write python program to create and use a user defined
18 package for a given problem
2. Method Overriding
Practical No. 26: Implement Python Program to Load a CSV file into a Pandas
26 DataFrame and Perform Operations.
Practical No. 27: Write python GUI program to import Tkinter package and
27 create a window and set its title
Practical No. 28: Write Python GUI Program that Adds Labels and Buttons to
28 the Tkinter Window
Practical No. 30: Implement Python Program to Select Records from the
30
Database Table and Display the Result
● Visit the official website of the IDE you've chosen (e.g., PyCharm or VS Code).
● Download the appropriate version for your operating system (Windows, macOS,
Linux).
● Run the downloaded installer file and follow the on-screen instructions.
● For VS Code, you may also want to install the Python extension for added features.
PROGRAM NO. 1
print("Hello, world!")
print()
print("I am a student in the 2nd year of Polytechnic.")
OUTPUT
Hello, world!
num1 = 10
num2 = 5
# Logical Operators
x = True
y = False
# Bitwise Operators
a = 4 # Binary: 100
b = 2 # Binary: 010
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Logical AND: False
Bitwise AND: 0
Bitwise OR: 6
Bitwise XOR: 6
Bitwise NOT: -5
number = 5
if number > 0:
age = 18
else:
marks = 85
else:
else:
OUTPUT
The number is positive.
count = 1
OUTPUT
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
print("Using 'continue':")
if i == 3:
print("Number:", i)
print("\nUsing 'pass':")
if i == 3:
print("Number:", i)
print("\nUsing 'break':")
if i == 3:
print("Number:", i)
OUTPUT
Using 'continue':
Number: 1
Number: 2
Number: 4
Number: 5
Using 'pass':
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Using 'break':
Number: 1
Number: 2
# 1. Create a list
print("\nAccessing elements:")
# Add an item
my_list.append("orange")
# Remove an item
my_list.remove("banana")
OUTPUT
length = len(my_list)
maximum = max(my_list)
my_list.append(60)
count = my_list.count(20)
my_list.insert(2, 25)
if 30 in my_list:
my_list.remove(30)
else:
# Final result
OUTPUT
List after appending 60: [10, 20, 30, 40, 50, 60]
List after extending with [70, 80, 90]: [10, 20, 30, 40, 50, 60, 70, 80, 90]
List after inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60, 70, 80, 90]
Popped element: 30
List after popping element at index 3: [10, 20, 25, 40, 50, 60, 70, 80, 90]
Final List: [10, 20, 25, 40, 50, 60, 70, 80, 90]
print("Accessing elements:")
del my_tuple
print("Tuple deleted!") # This will cause an error if you try to access `my_tuple` after
deletion.
my_tuple = (60, 70, 80, 90, 100) # Recreating the tuple for demonstration
my_list = list(my_tuple)
new_tuple = tuple(my_list)
OUTPUT
Created Tuple: (10, 20, 30, 40, 50)
Accessing elements:
First element: 10
Last element: 50
Tuple deleted!
Converted List back into Tuple: (60, 70, 80, 90, 100)
# Note: Sets are unordered, so you cannot access elements using an index.
# However, you can loop through the set to access its elements.
print("Accessing elements:")
print()
my_set.add(60)
my_set.discard(20)
del my_set
print("Set deleted!")
OUTPUT
Accessing elements:
50 20 40 10 30
Set after adding 60: {50, 20, 40, 10, 60, 30}
Set after adding [70, 80, 90]: {70, 10, 80, 20, 90, 30, 40, 50, 60}
Set after discarding 20 (if present): {70, 10, 80, 90, 30, 40, 50, 60}
Set after removing 30: {70, 10, 80, 90, 40, 50, 60}
Set deleted!
# Display results
print("Set 1:", set1)
print("Set 2:", set2)
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference (Set1 - Set2):", difference_set)
print("Symmetric Difference:", symmetric_difference_set)
OUTPUT
Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (Set1 - Set2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Practical No. 12: Write a Python program to perform the following operations
on the Dictionary: Create, Access, Update, Delete, Looping through the
Dictionary, and Create a Dictionary from the list.
# Creating a dictionary
student_info = {"name": "Alice", "age": 20, "course": "Computer Science"}
print("Initial Dictionary:", student_info)
# Accessing values in a dictionary
print("Name:", student_info["name"]) # Accessing value by key
# Updating a dictionary
student_info["age"] = 21 # Updating an existing key
student_info["grade"] = "A" # Adding a new key-value pair
print("Updated Dictionary:", student_info)
# Deleting items in a dictionary
del student_info["course"] # Deleting a key-value pair
print("Dictionary after deletion:", student_info)
# Looping through the dictionary
print("Dictionary items:")
for key, value in student_info.items():
print(f"{key}: {value}")
# Creating a dictionary from a list
keys = ["name", "age", "grade"]
values = ["Bob", 22, "B"]
new_dict = dict(zip(keys, values))
print("Dictionary from List:", new_dict)
OUTPUT
Initial Dictionary: {'name': 'Alice', 'age': 20, 'course': 'Computer Science'}
Name: Alice
Updated Dictionary: {'name': 'Alice', 'age': 21, 'course': 'Computer Science',
'grade': 'A'}
Dictionary after deletion: {'name': 'Alice', 'age': 21, 'grade': 'A'}
Dictionary items:
name: Alice
age: 21
grade: A
Dictionary from List: {'name': 'Bob', 'age': 22, 'grade': 'B'}
Process finished with exit code 0
Practical No. 13: Write a user-defined function to implement the
following features: Function without argument, Function with
argument, Function returning value.
# Function without argument
def greet():
def greet_person(name):
return a + b
print("Sum:", result)
OUTPUT
Sum: 8
return a * b
def greet(name="Guest"):
print(f"Hello, {name}!")
def add_numbers(*numbers):
return sum(numbers)
OUTPUT
Hello, Guest!
Hello, Bob!
Sum: 15
OUTPUT
Square of 5: 25
Squared numbers: [1, 4, 9, 16, 25]
Sum of numbers: 15
Process finished with exit code 0
Practical No. 16: Write a python program to create and use a
user defined module for a given problem
# User-defined module (math_operations.py equivalent)
return a + b
return a - b
return a * b
if b != 0:
return a / b
else:
def square(n):
return n ** 2
# ------------------------------
# ------------------------------
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Square of 10 : 100
import random
import os
random.shuffle(sample_list)
# 3. Using OS module
Factorial of 5: 120
OS Module Demonstration:
def to_lower(text):
"""Function to convert text to lowercase."""
return text.lower()
# ------------------------------
# Using the Package Functions
# ------------------------------
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Uppercase: HELLO WORLD
Lowercase: hello world
Practical No. 19: Write a python program to use of numpy package
to perform operation on 2D matrix. Write a python program to use
of matplotlib package to represent data in graphical form
import numpy as np
# ------------------------------
# ------------------------------
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
# Matrix Addition
print("\nMatrix Addition:")
print(matrix_sum)
# Matrix Multiplication
print("\nMatrix Multiplication:")
print(matrix_product)
# Transpose of a Matrix
matrix_transpose = np.transpose(matrix1)
print(matrix_transpose)
# ------------------------------
# ------------------------------
x = np.arange(1, 6)
y = np.array([2, 4, 6, 8, 10])
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid()
plt.show()
OUTPUT
Matrix 1:
[[1 2 3]
[4 5 6]
[7 8 9]]
Matrix 2:
[[9 8 7]
[6 5 4]
[3 2 1]]
Matrix Addition:
[[10 10 10]
[10 10 10]
[10 10 10]]
Matrix Multiplication:
[[ 30 24 18]
[ 84 69 54]
Transpose of Matrix 1:
[[1 4 7]
[2 5 8]
[3 6 9]]
Practical No. 20: Develop a python program to perform following
operations:
1. Creating a Class with method 2. Creating Objects of class
3. Accessing method using object
# Creating a class with a method
class Student:
self.name = name
self.age = age
def display_info(self):
student1.display_info()
student2.display_info()
OUTPUT
def __init__(self):
self.name = "Unknown"
self.age = 0
def display_info(self):
student1 = Student()
student1.display_info()
class Person:
# Parameterized Constructor
self.name = name
self.age = age
def display_info(self):
person1.display_info()
class Example:
self.value = a
else:
self.value = 0
def display_value(self):
print(f"Value: {self.value}")
example1 = Example()
example2 = Example(5)
example1.display_value()
example2.display_value()
example3.display_value()
OUTPUT
return a + b + c
class Parent:
def show(self):
class Child(Parent):
# Method Overriding
def show(self):
# Method Overloading
obj1 = Example()
# Method Overriding
obj2 = Child()
OUTPUT
30
60
def __init__(self):
def show(self):
self.__private_var = value
# Creating object
obj = Example()
print(obj.show())
print(obj.show())
OUTPUT
class Child(Parent):
def func2(self):
return "Function in Child class"
class Parent2:
def funcB(self):
return "Function in Parent2 class"
class ParentMulti(Grandparent):
def funcY(self):
return "Function in ParentMulti class"
class ChildMulti(ParentMulti):
def funcZ(self):
return "Function in ChildMulti class"
print("\nMultiple Inheritance:")
obj2 = ChildMultiple()
print(obj2.funcA()) # Inherited from Parent1
print(obj2.funcB()) # Inherited from Parent2
print(obj2.funcC()) # Child's own method
print("\nMultilevel Inheritance:")
obj3 = ChildMulti()
print(obj3.funcX()) # Inherited from Grandparent
print(obj3.funcY()) # Inherited from ParentMulti
print(obj3.funcZ()) # Child's own method
OUTPUT
Multilevel Inheritance:
Function in Grandparent class
Function in ParentMulti class
Function in ChildMulti class
import pandas as pd
series_from_array = pd.Series(array_data)
series_from_list = pd.Series(list_data)
list_dataframe = pd.DataFrame([[1, 'Alice', 25], [2, 'Bob', 30], [3, 'Charlie', 35]],
0 10
1 20
2 30
3 40
dtype: int32
0 100
1 200
2 300
3 400
dtype: int64
ID Name Age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35
ID Name Salary
filtered_data = df[df['Age'] > 25] # Replace 'Age' with actual column name
df.fillna(df.mean(numeric_only=True), inplace=True)
OUTPUT
First 5 rows:
Statistical Summary:
ID Age Salary
window = tk.Tk()
window.mainloop()
OUTPUT
+--------------------------------------+
|--------------------------------------|
| |
| |
| |
Practical No. 28: Write python GUI program that adds labels and
buttons to the
Tkinter window
import tkinter as tk
window = tk.Tk()
# Create a label
def on_button_click():
# Create a button
window.mainloop()
OUTPUT
+--------------------------------------+
|--------------------------------------|
| |
| |
| |
+--------------------------------------+
Practical No. 29: Write program to create a connection between
database and Python import sqlite3
cursor = connection.cursor()
# Create a table
name TEXT,
age INTEGER
)''')
# Commit changes
connection.commit()
rows = cursor.fetchall()
print("\nStudents Table:")
connection.close()
OUTPUT
Students Table:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
name TEXT,
age INTEGER
)''')
conn.commit()
rows = cursor.fetchall()
print(row)
conn.close()
OUTPUT
Student Records:
By Chaitanya