0% found this document useful (0 votes)
3 views20 pages

Python Programs

The document contains multiple Python programs demonstrating various functionalities such as ATM withdrawal, employee salary operations, set functions, dictionary manipulations, and SQLite database interactions. Each program includes user inputs, data processing, and outputs relevant information, showcasing operations like addition, updates, searches, and joins in databases. Overall, the document serves as a comprehensive guide for implementing basic programming concepts in Python.

Uploaded by

kunalnaphade28
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)
3 views20 pages

Python Programs

The document contains multiple Python programs demonstrating various functionalities such as ATM withdrawal, employee salary operations, set functions, dictionary manipulations, and SQLite database interactions. Each program includes user inputs, data processing, and outputs relevant information, showcasing operations like addition, updates, searches, and joins in databases. Overall, the document serves as a comprehensive guide for implementing basic programming concepts in Python.

Uploaded by

kunalnaphade28
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

Program4:

# ATM Withdrawal Program

# Taking valid balance input


while True:
try:
balance = int(input("Enter current account balance: "))
if balance < 0:
raise ValueError
break
except ValueError:
print("Invalid input! Balance must be a non-negative number.")

# Taking valid withdrawal amount


while True:
try:
amount = int(input("Enter withdrawal amount: "))
if amount <= 0:
raise ValueError
break
except ValueError:
print("Invalid input! Amount must be greater than zero.")

# Transaction check
try:
if amount > balance:
raise Exception("Insufficient balance")

except Exception as e:
print("Transaction Error:", e)
else:
balance -= amount
print("Withdrawal successful!")
print("Remaining balance:", balance)
finally:
print("Thank you for using the ATM.")

Output:
Program8:
# Sequence Operations on Employee Salaries
# Input employee salaries
n = int(input("Enter number of employees: "))
salary_list = []
for i in range(n):
sal = int(input(f"Enter salary of employee {i+1}: "))
salary_list.append(sal)

# Convert list to tuple (sequence)


salaries = tuple(salary_list)
print("\nEmployee Salaries:", salaries)

# Length of sequence
print("Total employees:", len(salaries))

# Maximum, Minimum, and Average salary


print("Highest salary:", max(salaries))
print("Lowest salary:", min(salaries))
print("Average salary:", sum(salaries) / len(salaries))

# Indexing
print("First employee salary:", salaries[0])
# Slicing
print("First three salaries:", salaries[:3])

# Membership operation
check = int(input("\nEnter salary to check: "))
print("Salary present:", check in salaries)

# Count occurrence
count_sal = int(input("Enter salary to count: "))
print("Occurrence count:", [Link](count_sal))
# Index of salary
if count_sal in salaries:
print("Index of salary:", [Link](count_sal))
# Sorting
print("Sorted salaries:", tuple(sorted(salaries)))
# Concatenation
bonus_salaries = (5000, 7000)
combined = salaries + bonus_salaries
print("After concatenation:", combined)

# Repetition
print("Repeated salaries:", salaries * 2)
# Traversing sequence
print("\nSalary List:")
for s in salaries:
print(s)40
Output:
Program9:
# Program to demonstrate all Set functions
# Create empty sets
set1 = set()
set2 = set()
# Input for Set 1
n1 = int(input("Enter number of elements in Set 1: "))
for i in range(n1):
[Link](int(input("Enter element: ")))
# Input for Set 2
n2 = int(input("\nEnter number of elements in Set 2: "))
for i in range(n2):
[Link](int(input("Enter element: ")))
# Display sets
print("\nSet 1:", set1)
print("Set 2:", set2)
# Set operations
print("\nUnion:", [Link](set2))
print("Intersection:", [Link](set2))
print("Difference (Set1 - Set2):", [Link](set2))
print("Symmetric Difference:", set1.symmetric_difference(set2))
# Membership
x = int(input("\nEnter element to check in Set 1: "))
if x in set1:
print("Element is present in Set 1")
else:
print("Element is not present in Set 1")
# Length
print("Number of elements in Set 1:", len(set1))
Output:
Program10:
# Create empty dictionary
d = {}
# Input elements
n = int(input("Enter number of key-value pairs: "))
for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value
print("\nInitial Dictionary:", d)

# add / update using assignment


key = input("\nEnter key to add/update: ")
value = input("Enter value: ")
d[key] = value
print("After add/update:", d)

# update()
temp = {}
k = input("\nEnter key for update(): ")
v = input("Enter value: ")
temp[k] = v
[Link](temp)
print("After update():", d)

# setdefault()
key = input("\nEnter key for setdefault(): ")
value = input("Enter default value: ")
[Link](key, value)
print("After setdefault():", d)
# get()
key = input("\nEnter key to get value: ")
print("Value:", [Link](key, "Key not found"))

# keys()
print("\nKeys:", [Link]())

# values()
print("Values:", [Link]())

# items()
print("Items:", [Link]())

# membership
key = input("\nEnter key to check membership: ")
print("Key present:", key in d)

# pop()
key = input("\nEnter key to delete using pop(): ")
print("Removed value:", [Link](key, "Key not found"))
print("After pop():", d)

# length
print("Number of elements:", len(d))

# clear()
[Link]()
print("\nAfter clear():", d)
Output:
Program11:
import sqlite3

# Connect to database
conn = [Link]("[Link]")
cur = [Link]()
[Link]("DROP TABLE IF EXISTS student")
# Create table (roll_no is PRIMARY KEY → no duplicates)
[Link]("""
CREATE TABLE IF NOT EXISTS student (
roll_no INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
""")

# Insert records (duplicates not allowed)


n = int(input("Enter number of students: "))
for i in range(n):
r = int(input("Enter Roll No: "))
name = input("Enter Name: ")
m = int(input("Enter Marks: "))

[Link](
"INSERT OR IGNORE INTO student VALUES (?, ?, ?)",
(r, name, m)
)

[Link]()

# Display records after insert


print("\nStudent Records After Insert:")
[Link]("SELECT * FROM student")
for row in [Link]():
print(row)

# Update record
r = int(input("\nEnter Roll No to update marks: "))
new_marks = int(input("Enter new marks: "))
[Link](
"UPDATE student SET marks=? WHERE roll_no=?",
(new_marks, r)
)
[Link]()

# Display records after update


print("\nStudent Records After Update:")
[Link]("SELECT * FROM student")
for row in [Link]():
print(row)

# Delete record
r = int(input("\nEnter Roll No to delete record: "))
[Link]("DELETE FROM student WHERE roll_no=?", (r,))
[Link]()

# Display records after delete


print("\nStudent Records After Delete:")
[Link]("SELECT * FROM student")
for row in [Link]():
print(row)
# Close connection
[Link]()

Output:
Program12:

import sqlite3

# Connect to database
conn = [Link]("[Link]")
cur = [Link]()

# Create table
[Link]("""
CREATE TABLE IF NOT EXISTS tweets (
tweet_id INTEGER PRIMARY KEY,
username TEXT,
tweet_text TEXT
)
""")
[Link]()

# ---------------- Insert tweets (simulated) ----------------


n = int(input("Enter number of tweets: "))
for i in range(n):
tid = int(input("Enter Tweet ID: "))
user = input("Enter Username: ")
text = input("Enter Tweet Text: ")

[Link](
"INSERT OR IGNORE INTO tweets (tweet_id, username, tweet_text) VALUES (?, ?, ?)",
(tid, user, text)
)

[Link]()
# ---------------- Display all tweets ----------------
print("\nAll Stored Tweets:")
[Link]("SELECT * FROM tweets")
for row in [Link]():
print(row)

# ---------------- Search Options ----------------


print("\nSearch Options")
print("1. Search by Tweet ID")
print("2. Search by Username")
print("3. Search by Keyword in Tweet Text")

choice = int(input("Enter your choice: "))

if choice == 1:
tid = int(input("Enter Tweet ID to search: "))
[Link]("SELECT * FROM tweets WHERE tweet_id=?", (tid,))
result = [Link]()
if result:
print("Tweet Found:", result)
else:
print("Tweet not found")

elif choice == 2:
user = input("Enter Username to search: ")
[Link]("SELECT * FROM tweets WHERE username=?", (user,))
results = [Link]()
if results:
print("Tweets Found:")
for row in results:
print(row)
else:
print("No tweets found for this user")

elif choice == 3:
keyword = input("Enter keyword to search in tweets: ")
[Link]("SELECT * FROM tweets WHERE tweet_text LIKE ?", ('%'+keyword+'%',))
results = [Link]()
if results:
print("Tweets containing keyword:")
for row in results:
print(row)
else:
print("No tweets found with this keyword")

else:
print("Invalid choice")

# Close database
[Link]()
Output:
Program13:
import sqlite3
# Connect to SQLite database
con = [Link]("[Link]")
cur = [Link]()
# Create tables
[Link]("""
CREATE TABLE IF NOT EXISTS Department (
deptid INTEGER PRIMARY KEY,
deptname TEXT
)
""")
[Link]("""
CREATE TABLE IF NOT EXISTS Student (
id INTEGER PRIMARY KEY,
name TEXT,
deptid INTEGER,
FOREIGN KEY(deptid) REFERENCES Department(deptid)
)
""")
# Insert Department details (user input)
n = int(input("Enter number of departments: "))
for i in range(n):
deptid = int(input("Enter Department ID: "))
deptname = input("Enter Department Name: ")
[Link]("INSERT OR IGNORE INTO Department VALUES (?, ?)", (deptid, deptname))
# Insert Student details (user input)
m = int(input("\nEnter number of students: "))
for i in range(m):
sid = int(input("Enter Student ID: "))
name = input("Enter Student Name: ")
deptid = int(input("Enter Department ID: "))
[Link]("INSERT OR IGNORE INTO Student VALUES (?, ?, ?)", (sid, name, deptid))
# JOIN query
print("\nStudent Details with Department")
print("--------------------------------")
[Link]("""
SELECT [Link], [Link], [Link]
FROM Student
INNER JOIN Department
ON [Link] = [Link]
""")
# Display result
for row in [Link]():
print(row)
# Commit and close
[Link]()
[Link]()
Output:

You might also like