[Go to site: main page, start]

0% found this document useful (0 votes)
2 views45 pages

Python Programs for Basic Arithmetic and File Operations

The document outlines various Python programs aimed at performing arithmetic operations, generating Fibonacci series, calculating factorials, handling exceptions, and managing database operations using MySQL. Each program has a specific aim, such as creating menus for user interaction, reading and writing files, and executing SQL commands. The document serves as a collection of programming exercises demonstrating different functionalities in Python and SQL.

Uploaded by

ih574414
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)
2 views45 pages

Python Programs for Basic Arithmetic and File Operations

The document outlines various Python programs aimed at performing arithmetic operations, generating Fibonacci series, calculating factorials, handling exceptions, and managing database operations using MySQL. Each program has a specific aim, such as creating menus for user interaction, reading and writing files, and executing SQL commands. The document serves as a collection of programming exercises demonstrating different functionalities in Python and SQL.

Uploaded by

ih574414
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

INDEX

[Link] Name of the program Date Remark Sign


Program:-1
Aim:- creating a menu driven program to perform arithmetic
operations.

def add (x, y):


return x + y
def subtract (x, y):
return x - y
def multiply (x, y):
return x * y

def divide (x, y):


if y == 0:
return "Error! Division by zero."

return x / y

def menu ():

print ("\nSelect operation:")


print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplication")
print ("4. Division")
print ("5. Exit")
while True:
menu ()

choice = input ("Enter choice (1/2/3/4/5): “)


if choice == '5':
print ("Exiting program. Goodbye!")
break
if choice in ['1', '2', '3', '4']:

num1 = float (input ("Enter first number: "))


num2 = float (input ("Enter second number: "))
if choice == '1':
print (f"The result of addition is: {add (num1, num2)}")
elif choice == '2':
print (f"The result of subtraction is:
{subtract(num1, num2)}")
elif choice == '3':
print(f"The result of multiplication is: {multiply
(num1, num2)}")
elif choice == '4':

print (f"The result of division is: {divide (num1, num2)}")


else:
print ("Invalid input! Please choose a valid option.")
Output:
Program:-2
Aim:-create a python program to display Fibonacci series.

i =int (input ("enter the limit:"))


x=0
y=1
z=1
print ("Fibonacci series \n")
print (x, y,end= " ")
while (z<= i):
print (z, end=" ")
x=y
y=z
z=x+y
output:-
Program:-3
Aim:- Creating a menu driven program to find the factorial
and sum of the list to number using function.

num = int (input ("Enter the number for calculating its factorial:
"))
fact = 1
i=1
while i<=num: fact = fact*i
i=i+1
print ("The factorial of ", num,"=", fact)
Program :-4

Aim :- Write a Program to find factorial of the entered number.

num = int(input("Enter the number for calculating its factorial : "))


fact = 1
i=1
while i<=num:
fact = fact*i

i=i+1
print("The factorial of ",num,"=",fact)

Output:-
Program :-5

Aim:- Write a python program to generate random number


between 1 to 6.
import random
number = [Link](1,6)
print(number)
Program :-6
Aim : - Creating a python program to implement
mathematical functions.

import math

def menu ():


print ("\nSelect a mathematical operation:")
print ("1. Square Root")
print ("2. Power (x^y)")
print ("3. Logarithm (base 10)")
print ("4. Exit")

while True:

menu ()
# Get user's choice

choice = input ("Enter your choice (1-4):")

# Perform operations based on the user's choice


if choice == '1':
num = float (input ("Enter a number to find the square
root: "))
if num < 0:
print ("Square root is not defined for negative
numbers.")
else:
print(f"Square root of {num} is: {[Link](num)}")

elif choice == '2':


base = float (input ("Enter the base number (x): "))
exp = float (input ("Enter the exponent (y): "))
print(f"{base} raised to the power of {exp} is:
{[Link](base, exp)}")

elif choice == '3':


num = float (input ("Enter a number to find its logarithm
(base 10): "))
if num <= 0:
print ("Logarithm is not defined for zero or negative
numbers.")

else:
print(f"Logarithm (base 10) of {num} is:
{math.log10(num)}")

elif choice == '4':


print ("Exiting program. Goodbye!")
break
else:
print ("Invalid choice! Please select a valid option from the
menu.")
Program:-7

Aim:-Determine whether a number is a perfect number, an


Armstrong numberor a palindrome.
Program:-8
Aim:- input a number and check if the number is prime or
composite numbert
Program:-9

Python Program to add marks and calculate the grade of a


student
Outrput:-
Program:- 10
Aim: - write a python program that takes two numbers as input from the user
and calculates the quotient of the two numbers. Handle the exceptions that
may occur during the program execution, such as invalid input or division by
zero.

try:
num1 = int(input("enter a number:"))
num2 = int(input("enter a number:"))
result = num1/num2
print(result)
except ValueError as e:
print("invalid input please input integer")
except ZeroDivisionError as e:
print(e)

output:-
Program :-11

Aim:-To write a Python Program to Read a text file


"[Link]" line by line and display each word separated by
'#'.

f = open(“[Link]”,’r’)
Contents= [Link]()
for line in contents:
words = [Link]()
for i in words:
print( i + ‘#’,end=’ ‘)
print(“ “)
[Link]()
Program:-12

Aim:-CREATING A PYTHON PROGRAM TO


COPY PARTICULAR LINES OF A TEXT FILE
INTO AN ANOTHER TEXT FILE.

F1 = open(“[Link]”,’r’)
F2 = open(“[Link]”,’w’)
S= [Link]( )
For i in S:
If i[0]==’A’ or i[0]==’a’:
[Link](i)
print(“written successfully”)
[Link]() [Link]()
Program:-13
Aim:-To write a Python Program to Create a binary file
with roll number and name. Search for a given roll number
and display the name, if not found display appropriate
message.
Output:-
Program:-14

Aim:-To write a Python program Create a CSV file to store


Empno, Name, Salary and search any Empno and display
Name, Salary and if not found display appropriate message.
Output:-
Program:-15

Aim:- write a program to implement a stack for the


employee details(empno, name) .
Output:-
PROGRAM :– 16

AIM:- CREATE STUDENT TABLE IN DATABASE AND INSERT


VALUES INTO TABLE.

SQL> create table student(rno number(10),name char(10),fname char(10),course


char(10),address varchar(20));
Table created.

SQL> describe student;

Name Null? Type

----------------------------------------- -------- ----------------------------

RNO NUMBER(10)

NAME CHAR(10)

FNAME CHAR(10)

COURSE CHAR(10)
ADDRESS VARCHAR2(20)

SQL> insert into student values(1,'lucky','sanjay','com','bharatvihar');

1 row created.

SQL> insert into student values(2,'manish','pawan','sci','delhi');

1 row created.
SQL> insert into student values(3,'mohit','ajay','arts','begumpur');

1 row created.

SQL> insert into student values(4,'sohil','rajesh','com','rohini'); 1

row created.

SQL> insert into student values(5,'rohit','monu','comm','delhi'); 1

row created.

SQL> select * from student;

RNO NAME FNAME COURSE ADDRESS

---------- ---------- ---------- ---------- ------------------------


1 lucky sanjay comm bharatvihar

2 manish pawan sci delhi

3 mohit ajay arts begumpur

4 sohil rajesh comm rohini

5 rohit monu comm delhi


PROGRAM :– 17

AIM :– ALTER COMMAND ON TABLE FOR ADDING,


DROPPING, AND MODIFYING THE COLUMNS.

SQL> create table abc(eid number(10),ename char(10),edepartment


char(10),esalary number(10));
Table created.

SQL> describe abc;

Name Null? Type

----------------------------------------- -------- ------------------------

EID NUMBER(10)

ENAME CHAR(10)

EDEPARTMENT CHAR(10)

ESALARY NUMBER(10)

SQL> insert into abc values(1,'amit','sales',20000);

1 row created.

SQL> insert into abc values(2,'manish','markiting',30000);

1 row created.

SQL> insert into abc values(3,'manisha','marketing',35000);

1 row created.

SQL> insert into abc values(4,'mohit','sales',20000);


1 row created.

SQL> insert into abc values(5,'rohit','sales',20000);

1 row created.

SQL> select * from abc;

EIDE NAME EDEPARTMEN ESALARY

---------- ---------- ---------- ---------------------


1 amit sales 20000

2 manish markiting 30000


3 manisha marketing 35000
4 mohit sales 20000

5 rohit sales 20000

SQL> alter table abc add(inc number(10));

Table altered.

SQL> describe abc;

Name Null? Type

----------------------------------------- -------- ----------------------------

EID NUMBER(10)

ENAME CHAR(10)

EDEPARTMENT CHAR(10)

ESALARY NUMBER(10)

INC NUMBER(10)

SQL> alter table abc drop column inc;


Table altered.

SQL> describe abc;

Name Null? Type

----------------------------------------- -------- ----------------------------

EID NUMBER(10)

ENAME CHAR(10)

EDEPARTMENT CHAR(10)

ESALARY NUMBER(10)

SQL> alter table abc modify(ename char(20));

Table altered.

SQL> describe abc;

Name Null? Type

----------------------------------------- -------- ----------------------------

EID NUMBER(10)

ENAME CHAR(20)

EDEPARTMENT CHAR(10)

ESALARY NUMBER(10)
Program -18

Aim :- Write a Program to show MySQL database connectivity in


python.

import [Link]

con=[Link](host='localhost',user='root',password='',db='s
chool')
stmt=[Link]()

query='select * from student;'

[Link](query)

data=[Link]()

print(data)

Output:-
PROGRAM :– 19 (A)

Q1:- to write sql queries for the following questions based on the given table.
PROGRAM :– 19 (B)
Q2:- to write sql queries for the following questions based on the given table.
PROGRAM :– 19 (C)

Q3:- to write sql queries for the following questions based on the given table.
Program - 20

Aim:- Perform all the operations with reference to table ‘Employee’


through MySQL-Python connectivity
import MySQLdb

db1 = [Link]("localhost","root","","TESTDB" )

cursor = [Link]()

sql = "CREATE TABLE EMP(empno integer primary key,ename


varchar(25) not null,salary float);"

[Link](sql)

[Link]()
Inserting a record in ‘emp’
import MySQLdb

db1 = [Link]("localhost","root","","TESTDB" )

cursor = [Link]()

sql = "INSERT INTO EMP VALUES (1,'ANIL KUMAR',86000);"

try:

[Link](sql)

[Link]()

except:

[Link]()

[Link]()
Fetching all the records from EMP table having salary more than
70000.
import MySQLdb

db1 = [Link]("localhost","root","","TESTDB" )

cursor = [Link]()

sql = "SELECT * FROM EMP WHERE SALARY > 70000;"

try:

[Link](sql)

resultset = [Link]()

for row in resultset:

print (row)

except:

print ("Error: unable to fetch data")

[Link]()
Updating record(s) of the table using UPDATE
import MySQLdb

db1 = [Link]("localhost","root","","TESTDB" )

cursor = [Link]()

sql = "UPDATE EMP SET salary = salary +1000 WHERE salary<80000;"

try:
[Link](sql)

[Link]()

except:

[Link]()

[Link]()

Deleting record(s) from table using DELETE I


mport MySQLdb

db1 = [Link]("localhost","root","","TESTDB" )

cursor = [Link]()

sal=int(input("Enter salary whose record to be deleted : "))

sql = "DELETE FROM EMP WHERE salary =sal”

try:
[Link](sql)
print([Link], end=" record(s) deleted ")

[Link]()

except:
[Link]()

[Link]()

You might also like