0% found this document useful (0 votes)
22 views29 pages

Python Programs for Data Processing

The document contains multiple Python programs demonstrating various functionalities such as filtering odd numbers from a list, iterating through numbers, performing basic arithmetic operations, and manipulating tuples. It also includes a student details management system using a dictionary and a GUI application for database operations with MySQL. Each program is accompanied by sample inputs and outputs to illustrate their functionality.

Uploaded by

studytowin12d
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)
22 views29 pages

Python Programs for Data Processing

The document contains multiple Python programs demonstrating various functionalities such as filtering odd numbers from a list, iterating through numbers, performing basic arithmetic operations, and manipulating tuples. It also includes a student details management system using a dictionary and a GUI application for database operations with MySQL. Each program is accompanied by sample inputs and outputs to illustrate their functionality.

Uploaded by

studytowin12d
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

Program

N=input("Enter the numbers separated by spaces: ")​


numbers = list(map(int, [Link]()))​
odd_numbers = [num for num in numbers if num%2 != 0]​
print("Orignal list: ", numbers)​
print("List after removing even numbers: ", odd_numbers)

Output
Enter the numbers separated by spaces: 1 2 3 4 5 6 7 8 9 10

Orignal list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List after removing even numbers: [1, 3, 5, 7, 9]


Program
i = 1​
while i <=10:​
​ print(i)​
​ i +=1

Output
1

10
Program
[Link]

def add(a,b):​
​ return a+b​
def sub(a, b):​
​ return a-b

[Link]

def reverse(text):​
​ return text[::-1]

[Link]

from myPackage import math, string​


print([Link](5, 3))​
print([Link](10, 4))​
print([Link]("Hello"))

Output
8

olleH
Program
N=int(input("Enter the no. of words: "))​
wordList=[]​
for i in range(N):​
​ word = input("Enter: ")​
​ [Link](word)​
count=0​
print("Words with same first and last character:")​
List2=[]​
for i in wordList:​
​ if i[0].lower() == i[-1].lower():​
​ [Link](i)​
​ count+=1​
print(List2)​
print("Count: ", count)

Output
Enter the no. of words: 5

Enter: racer

Enter: Rear

Enter: Pop

Enter: charge

Enter: Tax

Words with same first and last character:

['racer', 'Rear', 'Pop']

Count: 3
Program

l=[]​
length=int(input("Enter the length of the list:"))​
for i in range(length):​
​ [Link](int(input("Enter: ")))​
if l==[]:​
​ print("Empty List")​
else:​
​ print("List is not empty")​
ndList=[]​
print("Original List:")​
print(l)​
for i in range(length):​
​ val=[Link]()​
​ if val in l:​
​ pass​
​ else:​
​ [Link](0, val)​
print("List without duplication:")​
print(ndList)

Output

Enter the length of the list:10

Enter: 1

Enter: 1

Enter: 2

Enter: 2

Enter: 3

Enter: 3

Enter: 4

Enter: 4

Enter: 5

Enter: 5

List is not empty

Original List:
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

List without duplication:

[1, 2, 3, 4, 5]


Program
def maximum(iter):​
​ maxVal = iter[0]​
​ for x in iter:​
​ if maxVal < x:​
​ maxVal = x​
​ return maxVal​
def minimum(iter):​
​ minVal = iter[0]​
​ for x in iter:​
​ if minVal > x:​
​ minVal = x​
​ return minVal​
tupList=[]​
length=int(input("Enter the length of the list:"))​
print("Enter the values as (a, b) for tuples in list:")​
for i in range(length):​
​ a = int(input("a: "))​
​ b = int(input("b: "))​
​ print()​
​ [Link]((a,b))​
print("List of Tuples:")​
print(tupList)​
productList=[a*b for (a,b) in tupList]​
maxIndex=[Link](maximum(productList))​
minIndex=[Link](minimum(productList))​
print(f"Tuple in list with Maximum Product of {productList[maxIndex]} is
{tupList[maxIndex]}")​
print(f"Tuple in list with Minimum Product of {productList[minIndex]} is
{tupList[minIndex]}")​
alist=[(x,y) for (x,y)in tupList if x>y]​
blist=[(x,y) for (x,y)in tupList if x<y]​
print(f"Tuples with greater first value, count = {len(alist)}:")​
print(alist)​
print(f"Tuples with greater second value, count = {len(blist)}:")​
print(blist)​
DupeList=[t for t in tupList if t[0]==t[1]]​
print(f"Tuples containing duplicates, count={len(DupeList)}")​
print(DupeList)
Output
Enter the length of the list:5

Enter the values as (a, b) for tuples in list:

a: 1

b: 2

a: 2

b: 3

a: 3

b: 3

a: 3

b: 2

a: 2

b: 1

List of Tuples:

[(1, 2), (2, 3), (3, 3), (3, 2), (2, 1)]

Tuple in list with Maximum Product of 9 is (3, 3)

Tuple in list with Minimum Product of 2 is (1, 2)

Tuples with greater first value, count = 2:

[(3, 2), (2, 1)]

Tuples with greater second value, count = 2:

[(1, 2), (2, 3)]


Tuples containing duplicates, count=1

[(3, 3)]
Program
studentDetails={
​ "Student1":{
​ "Name":"Raj",
​ "RegNo":1,
​ "Marks":{
​ "Tamil":64,
​ "English":75,
​ "Maths":81,
​ "Science":83,
​ "Social Science":85
​ }
​ },
​ "Student2":{
"Name":"Ravi",
​ "RegNo":2,
​ "Marks":{
​ "Tamil":84,
​ "English":75,
​ "Maths":82,
​ "Science":86,
​ "Social Science":85
​ }
​ },
​ "Student3":{
"Name":"Deepak",
"RegNo":3,
​ "Marks":{
​ "Tamil":74,
​ "English":95,
​ "Maths":79,
​ "Science":83,
​ "Social Science":75
​ }
​ },
​ "Student4":{
"Name":"Govind",
​ "RegNo":4,
​ "Marks":{
​ "Tamil":24,
​ "English":70,
​ "Maths":80,
​ "Science":72,
​ "Social Science":84
​ }
​ },
​ "Student5":{
"Name":"Sandeep",
​ "RegNo":5,
​ "Marks":{
​ "Tamil":94,
​ "English":95,
​ "Maths":91,
​ "Science":83,
​ "Social Science":82
​ }
​ },
​ "Student6":{
"Name":"Pradeep",
​ "RegNo":6,
​ "Marks":{
​ "Tamil":81,
​ "English":76,
​ "Maths":81,
​ "Science":83,
​ "Social Science":74
​ }
​ },
​ "Student7":{
"Name":"Malik",
​ "RegNo":7,
​ "Marks":{
​ "Tamil":84,
​ "English":75,
​ "Maths":81,
"Science":81,
​ "Social Science":85
​ }
​ },
​ "Student8":{
"Name":"Rahul",
​ "RegNo":8,
​ "Marks":{
​ "Tamil":63,
​ "English":62,
​ "Maths":61,
​ "Science":75,
​ "Social Science":65
​ }
​ },
​ "Student9":{
"Name":"Rashid",
​ "RegNo":9,
​ "Marks":{
​ "Tamil":98,
​ "English":95,
​ "Maths":81,
​ "Science":82,
​ "Social Science":95
}
​ },
​ "Student10":{
"Name":"Faisal",
​ "RegNo":10,
​ "Marks":{
​ "Tamil":61,
​ "English":71,
​ "Maths":100,
​ "Science":98,
​ "Social Science":97
​ }
​ }
}

print("\nPrinting all the keys\n")


for x in studentDetails:
​ print(x)
​ if isinstance(studentDetails[x], dict):
​ for y in studentDetails[x]:
​ print(y)
​ if isinstance(studentDetails[x][y], dict):
​ for z in studentDetails[x][y]:
​ print(z)
​ print()
print("\nPrinting all the values\n")
for x in studentDetails:
​ for y in studentDetails[x]:
​ if isinstance(studentDetails[x][y], dict):
​ for z in studentDetails[x][y]:
print(studentDetails[x][y][z])
​ print()
​ else:
​ print(studentDetails[x][y])
for Student,Detail in [Link]():
​ print(Student)
​ for key, value in [Link]():
​ if isinstance(value, dict):
​ for subject,marks in [Link]():
​ print(subject, ":", marks)
​ else:
​ print(key, ":", value)
​ print()
RegNo=int(input("Enter the RegNo: "))
Name=input("Enter the name of the student: ").title()
Sub=input("Enter the subject: ").title()
for x in studentDetails:
​ if studentDetails[x]["Name"]==Name and studentDetails[x]["RegNo"]==RegNo:
​ print(f"{Name}'s marks in {Sub} is: ", studentDetails[x]["Marks"][Sub])


Output
Printing all the keys

Student1

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science
Student2

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student3

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student4

Name

RegNo

Marks

Tamil
English

Maths

Science

Social Science

Student5

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student6

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student7
Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student8

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Student9

Name

RegNo

Marks

Tamil

English

Maths
Science

Social Science

Student10

Name

RegNo

Marks

Tamil

English

Maths

Science

Social Science

Printing all the values

Raj

64

75

81

83

85

Ravi

2
84

75

82

86

85

Deepak

74

95

79

83

75

Govind

24

70

80

72

84

Sandeep

94

95
91

83

82

Pradeep

81

76

81

83

74

Malik

84

75

81

81

85

Rahul

63

62

61

75
65

Rashid

98

95

81

82

95

Faisal

10

61

71

100

98

97

Student1

Name : Raj

RegNo : 1

Tamil : 64

English : 75

Maths : 81

Science : 83

Social Science : 85
Student2

Name : Ravi

RegNo : 2

Tamil : 84

English : 75

Maths : 82

Science : 86

Social Science : 85

Student3

Name : Deepak

RegNo : 3

Tamil : 74

English : 95

Maths : 79

Science : 83

Social Science : 75

Student4

Name : Govind

RegNo : 4

Tamil : 24

English : 70

Maths : 80

Science : 72
Social Science : 84

Student5

Name : Sandeep

RegNo : 5

Tamil : 94

English : 95

Maths : 91

Science : 83

Social Science : 82

Student6

Name : Pradeep

RegNo : 6

Tamil : 81

English : 76

Maths : 81

Science : 83

Social Science : 74

Student7

Name : Malik

RegNo : 7

Tamil : 84

English : 75

Maths : 81
Science : 81

Social Science : 85

Student8

Name : Rahul

RegNo : 8

Tamil : 63

English : 62

Maths : 61

Science : 75

Social Science : 65

Student9

Name : Rashid

RegNo : 9

Tamil : 98

English : 95

Maths : 81

Science : 82

Social Science : 95

Student10

Name : Faisal

RegNo : 10

Tamil : 61

English : 71
Maths : 100

Science : 98

Social Science : 97

Enter the RegNo: 10

Enter the name of the student: faisal

Enter the subject: maths

Faisal's marks in Maths is: 100


Program
create database test;

use test;

create table students(id int auto_increment primary key, name varchar(100), age int);

import tkinter as tk​


from logging import exception​
from tkinter import messagebox​
import [Link]​
def get_connection():​
​ return [Link](​
​ host="localhost",​
​ user="root",​
​ password="123qwe",​
​ database="test"​
​ )​
def insert_data():​
​ name = entry_name.get()​
​ age = entry_age.get()​
​ if name=="" or age=="":​
[Link]("Error","All fields are required!")​
​ return​
​ try:​
​ conn = get_connection()​
​ cursor = [Link]()​
​ [Link]("insert into students(name, age) values(%s,%s)",(name, age))​
​ [Link]()​
​ [Link]()​
[Link]("Success", "Data inserted successfully!")​
​ except Exception as e:​
[Link]("Database Error", str(e))​
def fetch_data():​
​ try:​
​ conn = get_connection()​
​ cursor = [Link]()​
​ [Link]("select * from students")​
​ rows=[Link]()​
​ [Link]()​
result="\n".join([f"ID:{row[0]} | Name:{row[1]} | Age:{row[2]}" for row in rows])​
​ [Link]("Student Records",result if result else "No data found.")​
​ except Exception as e:​
[Link]("Database Error", str(e))​
def update_data():​
​ sid = entry_id.get()​
​ name = entry_name.get()​
​ age = entry_age.get()​
​ if sid=="" or name=="" or age=="":​
[Link]("Error","All fields(ID, Name, Age) are required for update!")​
​ return​
​ try:​
​ conn = get_connection()​
​ cursor = [Link]()​
​ [Link]("update students set name=%s, age=%s where id=%s",(name, age, sid))​
​ [Link]()​
​ [Link]()​
​ if [Link] == 0:​
[Link]("Not Found",f"No record with ID{sid}")​
​ else:​
[Link]("Success", "Record updated successfully!")​
​ except Exception as e:​
[Link]("Database Error", str(e))​
def delete_data():​
​ sid = entry_id.get()​
​ if sid=="":​
[Link]("Error","ID is required to delete a record!")​
​ return​
​ try:​
​ conn = get_connection()​
​ cursor = [Link]()​
​ [Link]("delete from students where id=%s",(sid,))​
​ [Link]()​
​ [Link]()​
​ if [Link] == 0:​
[Link]("Not Found",f"No record with ID{sid}")​
​ else:​
[Link]("Success", "Record deleted successfully!")​
​ except Exception as e:​
[Link]("Database Error", str(e))​

root = [Link]()​
[Link]("Tkinter + MySQL CRUD Example")​
[Link]("1200x600")​
[Link](root, text="STUDENT INFORMATION SYSTEM", bg="yellow", font="ARIAL,
40").pack(pady=5)​
[Link](root,text="ID(for Update/Delete):").pack(pady=5)​
entry_id = [Link](root, bg="green")​
entry_id.pack(pady=5)​
[Link](root,text="Name:").pack(pady=5)​
entry_name = [Link](root, bg="red", fg="blue")​
entry_name.pack(pady=5)​
[Link](root,text="Age:").pack(pady=5)​
entry_age = [Link](root, bg="gray")​
entry_age.pack(pady=5)​
[Link](root, text="Insert Data", width=20, command=insert_data).pack(pady=5)​
[Link](root, text="Fetch Data", width=20, command=fetch_data).pack(pady=5)​
[Link](root, text="Update Data", width=20, command=update_data).pack(pady=5)​
[Link](root, text="Delete Data", width=20, command=delete_data).pack(pady=5)​
[Link]()

Output
Program
def write_to_file(filename, content):​
​ try:​
​ with open(filename, 'w') as file:​
​ [Link](content)​
​ print("File written successfully.")​
​ except Exception as e:​
​ print(f"An error occurred while appending: {e}")


def read_file(filename):​
​ try:​
​ with open(filename,'r') as file:​
​ data=[Link]()​
​ print("File content:")​
​ print(data)​
​ except FileNotFoundError:​
​ print("File not found")​
​ except Exception as e:​
​ print(f"An error occurred while appending: {e}")


def append_to_file(filename,content):​
​ try:​
​ with open(filename, 'a') as file:​
​ [Link](content)​
​ print("Content appended successfully.")​
​ except Exception as e:​
​ print(f"An error occurred while appending: {e}")


if __name__=="__main__":​
​ filename="[Link]"​
​ write_to_file(filename,"Hello, this is the first line.\n")​
​ append_to_file(filename,"This line is appended.\n")​
​ read_file(filename)​
Output
File written successfully.

Content appended successfully.

File content:

Hello, this is the first line.

This line is appended.


Program​
def divide_numbers():​
​ try:​
​ num1=int(input("Enter numerator: "))​
​ num2 = int(input("Enter denominator: "))​
​ result = num1/num2​
​ except ZeroDivisionError:​
​ print("Error: Division by zero is not allowed.")​
​ except ValueError:​
​ print("Error: Please enter only integers.")​
​ else:​
​ print("Result:", result)​
​ finally:​
​ print("Execution completed (finally block).")​
divide_numbers()

Output
Enter numerator: a

Error: Please enter only integers.


Execution completed (finally block).

You might also like