0% found this document useful (0 votes)
18 views23 pages

Python Programs for Basic Calculations and File Operations

Uploaded by

Sudha Kore
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)
18 views23 pages

Python Programs for Basic Calculations and File Operations

Uploaded by

Sudha Kore
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

1. Program to add two numbers.

x = int(input('Enter integer value:'))

print('Value entered:', x)

print('Type:', type(x))

2. Program to find simple interest.

p = float(input('Enter principle'))

r = float(input('Enter rate'))

t = float(input('Enter time'))

i=p*r*t/100

print("Interest=",i)

3. Program to check whether a number is even or odd.

a=float(input('Enter a number'))

if a%2==0:

print(a,"is even")

else:

print(a,"is odd")
4. Program to check whether a number is divisible by 2 or 3 using nested if.

num=float(input('Enter a number'))

if num%2==0:

if num%3==0:

print ("Divisible by 3 and 2")

else:

print ("divisible by 2 not divisible by 3")

else:

if num%3==0:

print ("divisible by 3 not divisible by 2")

5. Menu based program to find sum, subtraction, multiplication and division

of values.

print("1. Sum of two numbers")

print("2. Subtaction of two numbers")

print("3. Multiplication of two numbers")

print("4. Division of two numbers")

choice=int(input('Enter your choice'))

if choice==1 :

a=int(input('Enter first number'))


b=int(input('Enter second number'))

c=a+b

print("Sum=",c)

elif choice==2 :

a=int(input('Enter first number'))

b=int(input('Enter second number'))

c=a-b

print("Subtraction=",c)

elif choice==3 :

a=int(input('Enter first number'))

b=int(input('Enter second number'))

c=a*b

print("Multiplication=",c)

elif choice==4 :

a=int(input('Enter first number'))

b=int(input('Enter second number'))

c=a/b

print("Division=",c)

else :

print("Wrong choice")

6. Program to print result depending upon the percentage.


a=int(input('Enter your percentage'))

eligible= a>=33

compartment = a>=20 and a<33

fail=a<20

if eligible :

print("Pass");

elif compartment :

print("compartment");

elif fail:

print("Fail");

7. Program to find sum of even numbers from 1 to 7.

sum=0

for num in range(8):

if num%2==0:

sum=sum+num

print("Sum of even values=",sum)

8. Program to find factorial of a number.

n=eval(input("Enter a number="))

i=1

f=1

while i<=n:
f=f*i #1*2*3*4*5

i=i+1

print("Factorial of",n,"=",f)

9. Program to print table of any number.

n=eval(input("Enter a number whose table you want="))

i=1

while i<=10:

print(n,"X",i,"=",n*i)

i=i+1

10. Program to print following pattern.

**

***

****

*****

for i in range(1,6):

print()

for j in range(1,i+1):

print ('*',end="")

11. Program to sort values in a list.


aList=[10,5,1,3]

print("Original List",aList)

n=len(aList)

for i in range(n-1):

for j in range(0,n-i-1):

if aList[j]>aList[j+1]:

aList[j],aList[j+1]=aList[j+1],aList[j]

print("Sorted List",aList)

12. Program to find minimum value in a list.

L=eval(input('Enter list values'))

length=len(L) #length=6

min=L[0] #min=10

loc=-1

for i in range(length): #0,1,2,3,4,5

if L[i]<min:

min=L[i] #min=1

loc=i

print("Minimum value=",min)

print("Location=",loc)

13. Program to check whether a value exists in dictionary

aDict={'Bhavna':1,"Richard":2,"Firoza":3,"Arshnoor":4}
val=eval(input('Enter value'))

flag=0

for k in aDict:

if val==aDict[k]:

print("value found at key",k)

flag=1

if flag==0:

print("value not found")

14. Program to find largest among two numbers using a user defined function

def largest():

a=int(input("Enter first number="))

b=int(input("Enter second number="))

if a>b :

print ("Largest value=%d"%a)

else:

print ("Largest value=%d"%b)

return

largest()

15. Program to find sum of two numbers using a user defined function with

parameters.
def sum(a,b): #a and b are formal parameters

c=a+b

print("sum=",c)

sum(4,5)

n1,n2=eval(input('Enter two values'))

sum(n1,n2)

16. Program to find simple interest using a user defined function with

parameters and with return value.

def interest(p1,r1,t1 ):

i=p*r*t/100

return(i)

p=int(input("Enter principle="))

r=int(input("Enter rate="))

t=int(input("Enter rate="))

in1=interest(p,r,t)

print("Interest=",in1)

17. Program to pass a list as function argument and modify it.

def changeme( mylist ):

print ("inside the function before change ", mylist)


mylist[0]=1000

print ("inside the function after change ", mylist)

return

list1 = [10,20,30]

print ("outside function before calling function", list1)

changeme( list1 )

print ("outside function after calling function", list1)

18. Program to use default arguments in a function.

def printinfo( name, age = 35 ): #default argument

print ("Name: ", name)

print ("Age ", age)

return

printinfo("aman",45)

printinfo("Parth")

19. Program to write rollno, name and marks of a student in a data file

[Link].

count=int(input('How many students are there in the class'))

fileout=open("[Link]","a")

for i in range(count):
print("Enter details of student",(i+1),"below")

rollno=int(input("Enter rollno:"))

name=input("name")

marks=float(input('marks'))

rec=str(rollno)+","+name+","+str(marks)+"\n"

[Link](rec)

[Link]()

20. Program to read and display contents of file [Link].

fileinp=open("[Link]","r")

while str:

str=[Link]()

print(str)

[Link]()

21. Program to read and display those lines from file that start with alphabet

‘T’.

file1=open("[Link]","r")

count=0

str1=[Link]()

print(str1)

for i in str1:

if i[0]=='T':
print (i)

[Link]()

22. Program to read and display those lines from file that end with alphabet

‘n’.

file1=open("[Link]","r")

count=0

str1=[Link]()

for i in str1:

if i[-2]=='n':

count+=1

print("Number of lines which end with 'n'=",count)

[Link]()

23. Program to count number of words in data file [Link].

file1=open("[Link]","r")

line=" "

count=0

while line:

line=[Link]()

s=[Link]()

for word in s:

count+=1
print("Number of words=",count)

[Link]()

24. Program to count number of characters in data file [Link].

file1=open("[Link]","r")

ch=" "

count=0

while ch:

ch=[Link](1)

count+=1

print("Number of characters=",count)

[Link]()

25. Program to write data in a csv file [Link].

import csv

fh=open("d:\[Link]","w")

stuwriter=[Link](fh)

[Link]([1,'aman',50])

[Link]([2,'Raman',60])

[Link]()

26. Program to readand display data from a csv file [Link].

import csv

fh=open("d:\[Link]","r")
stureader=[Link](fh)

for rec in stureader:

print(rec)

[Link]()

SQL Queries
SQL 1

(i) Display the Mobile company, Mobile name & price in descending order

of
their manufacturing date.

Ans. SELECT M_Compnay, M_Name, M_Price FROM MobileMaster

ORDER BY M_Mf_Date DESC;

(ii) List the details of mobile whose name starts with “S”.

Ans. SELECT * FROM MobileMaster

WHERE M_Name LIKE “S%‟;

(iii) Display the Mobile supplier & quantity of all mobiles except “MB003‟.

[Link] M_Supplier, M_Qty FROM MobileStock

WHERE M_Id <>”MB003”;

(iv) To display the name of mobile company having price between 3000 &

5000.

Ans. SELECT M_Company FROM MobileMaster

WHERE M_Price BETWEEN 3000 AND 5000;

**Find Output of following queries

(v) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;

MB004 450

MB003 400

MB003 300
MB003 200

(vi) SELECT MAX(M_Mf_Date), MIN(M_Mf_Date) FROM MobileMaster;

2017-11-20 2010-08-21

(vii) SELECT M1.M_Id, M1.M_Name, M2.M_Qty, M2.M_Supplier

FROM MobileMaster M1, MobileStock M2 WHERE M1.M_Id=M2.M_Id

AND M2.M_Qty>=300;

MB004 Unite3 450 New_Vision

Classic Mobile
MB001 Galaxy 300
Store

(viii) SELECT AVG(M_Price) FROM MobileMaster;


5450

SQL 2

i. Display the Trainer Name, City & Salary in descending order of

theirHiredate.

Ans. SELECT TNAME, CITY, SALARY FROM TRAINER

ORDER BY HIREDATE;

ii. To display the TNAME and CITY of Trainer who joined the Institute in

the month of December 2001.

Ans. SELECT TNAME, CITY FROM TRAINER

WHERE HIREDATE BETWEEN ‘2001-12-01’

AND ‘2001-12-31’;
iii. To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER

and COURSE of all those courses whose FEES is less than or equal to 10000.

Ans. SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE

WHERE [Link]=[Link] AND FEES<=10000;

iv. To display number of Trainers from each city.

Ans. SELECT CITY, COUNT(*) FROM TRAINER

GROUP BY CITY;

**Find Output of following queries

v. SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’,

‘MUMBAI’);

Ans.

103 DEEPTI

106 MANIPRABHA

vi. SELECT DISTINCT TID FROM COURSE;

Ans.

101

103

102

104

105
vii. SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID HAVING

COUNT(*)>1;

Ans.

101 2 12000

viii. SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE< ‘2018-

09-15’;

Ans.

4 65000

SQL 3

i) To display details of those Faculties whose salary is greater than 12000.

Ans: Select * from faculty

where salary > 12000;


ii) To display the details of courses whose fees is in the range of 15000 to

50000 (both values included).

Ans: Select * from Courses

where fees between 15000 and 50000;

iii ) To increase the fees of all courses by 500 of “System Design” Course.

Ans: Update courses set fees = fees + 500

where Cname = “System Design”;

(iv) To display details of those courses which are taught by ‘Sulekha’ in

descending order of courses.

Ans: Select * from faculty,courses

where faculty.f_id = course.f_id and [Link] = 'Sulekha'

order by cname desc;

**Find output of following

v) Select COUNT(DISTINCT F_ID) from COURSES;

Ans: 4

vi) Select MIN(Salary) from FACULTY,COURSES where COURSES.F_ID =

FACULTY.F_ID;

Ans: 6000

vii) Select sum(fees) from COURSES where F_ID = 102;

Ans: 60000
vii) Select avg(fees) from COURSES;

Ans: 17500

SQL 4

i. To display all the details of those watches whose name ends with ‘Time’

Ans select * from watches

where watch_name like ‘%Time’;

ii. To display watch’s name and price of those watches which have price

range in between 5000-15000.

Ans. select watch_name, price from watches

where price between 5000 and 15000;


iii. To display total quantity in store of Unisex type watches.

Ans. select sum(qty_store) from watches where type like ’Unisex’;

iv. To display watch name and their quantity sold in first quarter.

Ans. select watch_name,qty_sold from watches w,sale s

where [Link]=[Link] and quarter=1;

v. select max(price), min(qty_store) from watches;

Ans. 25000 100

vi. select quarter, sum(qty_sold) from sale group by quarter;

1 15

2 30

3 45

4 15

vii. select watch_name,price,type from watches w, sales where [Link]!

=[Link];

HighFashion 7000 Unisex

viii. select watch_name, qty_store, sum(qty_sold), qty_store-sum(qty_sold)

“Stock” from watches w, sale s where [Link]=[Link] group by

[Link];

HighTime 100 25 75

LifeTime 150 40 110


Wave 200 30 170

Golden Time 100 10 90

SQL 5

(i) To display the records from table student in alphabetical order as per the

name of the student.

Ans. Select * from student

order by name;

(ii ) To display Class, Dob and City whose marks is between 450 and 551.

Ans. Select class, dob, city from student

where marks between 450 and 551;

(iii) To display Name, Class and total number of students who have secured

more than 450 marks, class wise

Ans. Select name,class, count(*) from student

group by class
having marks> 450;

(iv) To increase marks of all students by 20 whose class is “XII

Ans. Update student

set marks=marks+20

where class=’XII’;

**Find output of the following queries.

(v) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY HAVING

COUNT(*)>1;

2 Mumbai

2 Delhi

2 Moscow

(vi ) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;

08-12-1995 07-05-1993

(iii) SELECT NAME,GENDER FROM STUDENT WHERE CITY=’Delhi’;

Sanal F

Store M

Common questions

Powered by AI

To optimize SQL queries for performance, especially with large datasets like mobile stock details, consider the following strategies: 1. **Indexing**: Ensure that frequently queried columns, such as `M_Id` for joining or filtering, have indexes to speed up retrieval time. 2. **Select Statements**: Use only necessary columns in SELECT queries to reduce data overhead, e.g., selecting specific fields (M_Company, M_Name, M_Price) instead of `*`. 3. **Joins**: Optimize joins by using keys and indexed fields, as shown in: ```sql SELECT M1.M_Id, M1.M_Name, M2.M_Qty, M2.M_Supplier FROM MobileMaster M1, MobileStock M2 WHERE M1.M_Id=M2.M_Id AND M2.M_Qty >= 300; ``` 4. **Query Simplification**: Avoid complex subqueries if possible; use views or temp tables for intermediary computations. 5. **Caching**: Implement query result caching in applications to reduce database loads for frequent queries. 6. **Analyzing Query Plans**: Use database tools to examine execution plans and identify bottlenecks in I/O operations or sorting phases. By following these methods, you can significantly improve performance and efficiency in database operations.

Counting words and characters in a data file is crucial for data analysis, helping determine text complexity or derive metrics for readability. Python facilitates this through file I/O operations and string manipulation. Here is an example: ```python file1 = open('data.txt', 'r') word_count = 0 for line in file1: words = line.split() word_count += len(words) print('Number of words=', word_count) file1.close() ``` This approach reads each line, splits it into words, and increments the count. Similarly, characters can be counted by reading one character at a time. ```python file1 = open('data.txt', 'r') char_count = 0 ch = file1.read(1) while ch: char_count += 1 ch = file1.read(1) print('Number of characters=', char_count) file1.close() ``` These methods help extract fundamental statistics about data, which can be used to assess document size and quality.

Reading and writing operations on data files in Python are essential for data persistence and retrieval. Writing records data like student details to a file allows information to be stored outside the program runtime, while reading it back into the program allows for processing or analysis. For writing: ```python fileout = open('Marks.dat', 'a') for i in range(count): # Collect data fileout.write(f'{rollno},{name},{marks}\n') fileout.close() ``` For reading: ```python fileinp = open('Marks.dat', 'r') for line in fileinp: print(line.strip()) fileinp.close() ``` Writing appends structured data, typically string-formatted, while reading retrieves it for display or processing. Challenges include handling file permissions and ensuring the file exists for reading.

To determine if a number is both even and divisible by 3, you can use nested if statements. The outer if checks if the number is divisible by 2 (even), and an inner if checks if the number is divisible by 3. For example: ```python num = float(input('Enter a number: ')) if num % 2 == 0: # Check if even if num % 3 == 0: # Check if divisible by 3 print('Divisible by 3 and 2') else: print('Divisible by 2 but not by 3') else: if num % 3 == 0: print('Divisible by 3 but not by 2') ```

Handling CSV files efficiently for student data involves utilizing Python's built-in csv module to read and write structured data conveniently. For writing, the process becomes straightforward when using csv.writer: ```python import csv with open('student.csv', 'w', newline='') as csvfile: stuwriter = csv.writer(csvfile) stuwriter.writerow([1, 'Aman', 50]) stuwriter.writerow([2, 'Raman', 60]) ``` This script opens a CSV file and writes data row-wise. The newline parameter prevents additional blank lines. For reading: ```python import csv with open('student.csv', 'r') as csvfile: stureader = csv.reader(csvfile) for rec in stureader: print(rec) ``` Efficient reading is achieved by iterating over each row. Specifying the delimiter is crucial when working with non-standard formats. Such operations enable organized storage and handling of tabular data, essential for educational records management and analysis.

User-defined functions allow you to encapsulate logic for reusability and organizing code. For instance, to find the largest of two numbers, a function can prompt for inputs and compare them using if-else constructs. ```python def largest(): a = int(input('Enter first number=')) b = int(input('Enter second number=')) if a > b: print('Largest value=%d' % a) else: print('Largest value=%d' % b) return largest() ``` This function compares two integers input by the user and prints the largest one.

To display mobile details in descending order of their manufacturing date, utilize the SQL ORDER BY clause. Here's how: ```sql SELECT M_Company, M_Name, M_Price FROM MobileMaster ORDER BY M_Mf_Date DESC; ``` This SQL query sorts mobile records from newest to oldest based on their manufacturing date. This approach is significant in reporting as it highlights the most recent products, assisting inventory management, and tracking technological trends and consumer demand. Such data organization is crucial for strategic decision-making concerning production, marketing, and sales forecasting in rapidly evolving industries like mobile technology.

To find the maximum price of a watch, the SQL query would be: ```sql SELECT MAX(price) FROM watches; ``` This query returns the highest price point across all watches. From a business analytics perspective, understanding the maximum price is vital for competitive pricing strategies and profitability analysis. It helps in positioning brands, delineating premium products, and customer segmentation based on purchasing power. Moreover, identifying high-price outliers can guide marketing campaigns to upscale markets. Business decisions like inventory stocking also benefit by ensuring premium items are available to prevent lost sales opportunities.

Default arguments in function definitions simplify code by allowing the omission of certain parameters when calling a function, making calls with fewer arguments possible and improving function flexibility. For instance: ```python def printinfo(name, age=35): print('Name:', name) print('Age:', age) ``` Here, the default age is set to 35. When `printinfo` is called with only the name, the function uses 35 as the age. This can reduce errors and enhance code clarity by providing sensible defaults for parameters that often do not change.

To find the minimum value and its location from a list entered by a user, you evaluate each element to determine if it is less than the current minimum, updating as required. Challenges include ensuring all edge cases, like negative numbers or duplicate values, are handled, and the algorithm efficiency in terms of time complexity, especially with larger lists. Here's a typical approach: ```python L = eval(input('Enter list values: ')) length = len(L) min_val = L[0] min_loc = 0 for i in range(1, length): # Start from 1 as 0 is already considered if L[i] < min_val: min_val = L[i] min_loc = i print('Minimum value=', min_val) print('Location=', min_loc) ``` This loop compares each item to the current minimum, updating as needed and outputs both the min value and its index.

You might also like