0% found this document useful (0 votes)
572 views

Project Ip

The document contains 15 questions related to Python programming. Each question provides sample code to solve a given problem, such as reversing a string, finding frequencies of list elements, calculating GST, slicing arrays, and more. The code examples demonstrate basic Python concepts like loops, functions, arrays, dataframes, plotting, and file handling.

Uploaded by

Dwarkesh savalia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
572 views

Project Ip

The document contains 15 questions related to Python programming. Each question provides sample code to solve a given problem, such as reversing a string, finding frequencies of list elements, calculating GST, slicing arrays, and more. The code examples demonstrate basic Python concepts like loops, functions, arrays, dataframes, plotting, and file handling.

Uploaded by

Dwarkesh savalia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Q.1. Write a program that reads a string and display it in reverse order.

ANSWER:
string1=input("Enter a string :")

print("The", string1, "in reverse order is:")


length=len(string1)

for a in range(-1, (-length-1),-1):

print(string1[a])

OUTPUT:

If input is PYTHON:
Q.2. Program to find frequencies of all elements of a list. Also, print the list
of unique elements in the list and duplicate elements in given list.

ANSWER:
lst=eval(input("Enter list:"))

length=len(lst)

uniq=[]

dupl=[]
count=i=0

while i<length:

element=lst[i]

count=1
if element not in uniq and element not in dupl:
i+=1

for j in range(i, length):


if element==lst[j]:
count+=1

else:

print("Element", element, "Frequency", count)

if count==1:
uniq.append(element)

else:
dupl.append(element)
else:

i+=1
print("ORIGINAL LIST : ", lst)

print("UNIQUE ELEMENTS LIST : ", uniq)

print("DUPLICATION ELEMENTS LIST : ", dupl)

OUTPUT:
Q.3. Write a program to create a dictionary containing names of the
competition winner students as keys and number of their wins as values.

ANSWER:
string1=input("Enter a string :")
print("The", string1, "in reverse order is:")

length=len(string1)
for a in range(-1, (-length-1),-1):

print(string1[a])

OUTPUT:
Q.4. Marks of three students “Suniti”, “Ryna” and “Zeba” in three subjects
are available in following three dictionaries respectively:
D1 = {1:40, 2:70, 3:70}

D2 = {1:40, 2:50, 3:60}

D3 = {1:70, 2:80, 3:90}

Create a nested dictionary that stores the marks details along with student
names and then prints the output as shown below:
Name

Ryna

Subject (key) Marks (value)


1 40

2 50
3 60

Name

Zeba
Subject (key) Marks (value)

1 70

2 80

3 90

Name
Suniti
Subject (key) Marks (value)

1 40

2 70

3 70

ANSWER:
D1 = {1:40, 2:70, 3:70}

D2 = {1:40, 2:50, 3:60}

D3 = {1:70, 2:80, 3:90}

D4 = {"Suniti":D1, "Ryna":D2, "Zeba":D3}

for x in D4.keys():
print("Name")
print(x)

print("Subject(keys)",'\t', "Marks(value)")
for y in D4[x].keys():

print(" ", y, '\t\t', D4[x][y])

print()

OUTPUT:

Q.6. Program to display a menu for calculating simple interest or


compound interest. Calculate compound interest as per the following
formula:
A=P (1+r/n) ^ nt

Where P=Principal amount

r=annual nominal interest rate


n=number of times the interest is compounded per year
t=number of years

ANSWER:
import math

principal=float(input("Enter principal amount:"))


rate=float(input("Enter annual rate of interest:"))

time=int(input("Enter time(in years):"))

print("1. Calculate Simple Interest")

print("2. Calculate Compound Interest")


choice=int(input("Enter your choice(1 or 2):"))
if choice==1:
interest=(principal*rate*time)/100

amount=principal+interest

print("Simple interest:{0:16.2f}".format(interest))

print("Amount after interest:{0:12.2f}".format(amount))


else:
n=int(input("Number of times interest is compounded in a year"))

rate=rate/100
periods=time*n

amount=principal*pow((1+rate/n), periods)

interest=amount-principal

print("Compound interest:{0:16.2f}".format(interest))

print("Amount after interest:{0:12.2f}".format(amount))


OUTPUT:

Q.5. Program to calculate the amount payable after sales discount, which is 10
10% up to the sales amount of 20000 and 17.5% on amounts above. (in
range 5-12%)
ANSWER:
salesamt=float(input("Enter sales amount:"))

if salesamt<=20000:

discountrate=10
else:

discountrate=17.5

discount=salesamt*discountrate/100

discount=salesamt*discountrate/100

afterdiscount=salesamt-discount

salestaxrate=float(input("Enter sales tax rate(5-12%):"))


salestax=afterdiscount*salestaxrate/100

netpayable=afterdiscount-salestax

print("Purchase Amount :", salesamt)

print("Discount Offered @", discountrate, "%:",discount)

print("Sales Tax @",salestaxrate, "%:", salestax)


print("Net Payable Amount :",netpayable)
OUTPUT:
Q.7. Program to accept transactions made in a day and items sold in day
for a week and then print average sales made per transaction.
8

ANSWER:
"""

trans=transaction made in a day;

items=items sold in a day

"""

totaltrans, totalsales =0,0


count=1
while count<=7:

trans=int(input("Transactions made on day"+str(count)+":"))

items=int(input("Items sold on day"+str(count)+":"))


totaltrans+=trans

totalsales+=items
count+=1

avgsales=totalsales/totaltrans

print("Total Sales Made:", totalsales)

print("Total Transactions Made:", totaltrans)

print("Average Sales Per Transaction:", avgsales)


OUTPUT:
Q.9. ABC shop deals in apparels and footwear. Write a program to
calculate total selling price after levying the GST. Do calculate Central
Government GST. GST rates as applicable as under:

Item GST Rate

Footwear < = 500 (per pair) 5%


Footwear >500 (per pair) 18%
Apparels < = 1000 (per piece) 5%

Apparels > 1000 (per piece) 12%

cgst : Central Government GST; sgst : State Government GST, SP: Selling
price; itc : itemcode

ANSWER:
itc=input("Enter item code (A) Apparel (F) Footwear:")

SP=float(input("Enter selling price (per unit) of item:"))


if itc=='a' or itc=='A':
item='Apparel'

if SP<=1000:

gstRate=5
else:

gstRate=12
elif itc=='f' or itc=='F':
item='Footwear'

if SP<=500:
gstRate=5

else:

gstRate=18
cgst=SP*(gstRate/2)/100

sgst=cgst

amount=SP+cgst+sgst #consumer will buy at this price

print('-'*65)

print("\t\t\t INVOICE")
print('-'*65)
print()

print("Item: {0:>40s}".format(item))

print("Price: \t\t{0:30.2f}".format(SP))

print("\t CGST (@",(gstRate/2),"%):\t\t {0:15.2f}".format(cgst))


print("\t SGST (@",(gstRate/2),"%):\t\t {0:15.2f}".format(cgst))
print('-'*65)

print("Amount payable : \t\t {0:23.2f}".format(amount))

print('-'*65)

OUTPUT:
Q.8. Write a program that reads from a csv file (csv1.csv stored in data
folder of D:drive having data as: Name and marks in 3 subjects) in a
dataframe. Then the program should add a column “Total” storing total of
marks in 3 subjects and another column storing average marks . Print the
dataframe.

ANSWER:
import pandas as pd
df=pd.read_csv("D:\\csv1.csv", names=["Name", "Marks1", "Marks2", "Marks3"
])

print("Dataframe after fetching data from csv file")

print(df)

df['Total']= df['Marks1']+df['Marks2']+df['Marks3']
df['AvgMarks']=df['Total'] /3
print("Dataframe after all the calculations")
print(df)

OUTPUT:

Q.10. Write a program to iterate over a DataFrame and print each data
value individually along with its row index and column name using iterrows().

ANSWER:
import pandas as pd
import numpy as np

disales = {2015:{'Qtr1':34500, 'Qtr2':56000, 'Qtr3':47000, 'Qtr4':49000},

2016:{'Qtr1':44900, 'Qtr2':46100, 'Qtr3':57000, 'Qtr4':59000},


2017:{'Qtr1':54500, 'Qtr2':51000, 'Qtr3':57000, 'Qtr4':58500}}

df1=pd.DataFrame(disales)

for (row, rowSeries) in df1.iterrows():


print("========================")
ind = rowSeries.index

i=0
for val in rowSeries:

print("[", row, "][", ind[i], "]: ",val)

i=i+1

OUTPUT:

Q.12. Write a program that reads from a csv file in a dataframe. (marks.csv)
Then the program should add a column “Total” storing total of marks in 3
subjects and another column storing average marks. Print the dataframe.

ANSWER:
import pandas as pd

df=pd.read_csv("D:\\marks.csv", names=["RollNo", "Name", "Marks1",


"Marks2", "Marks3", "Grade"])
print("Dataframe after fetching data from csv file")

print(df)

df['Total']= df['Marks1'] + df['Marks2'] + df['Marks3']


df['AvgMarks'] = df['Total'] /3

print("Dataframe after all the calculations")


print(df)

OUTPUT:

Q.11. Consider following ndarray:

A=array([10, 20, 30, 40, 50, 60, 70, 80, 90])

B=array([[0, 1, 2, 3],

[4, 5, 6, 7],
[8, 9, 10, 11],

[12, 13, 14, 15]])

What will be array slices as per following?


(A) B[0:2, 1:3]
(B) A[2:6:3]
(C) A[-1:-3]
(D) B[::-1]
(E) B[:3, 2:]
(F) B[:3, 6:2:-1]

ANSWER:
import numpy as np

A=np.array([10, 20, 30, 40, 50, 60, 70, 80, 90])

B=np.array([[0, 1, 2, 3],
[4, 5, 6, 7],

[8, 9, 10, 11],


[12, 13, 14, 15]])

OUTPUT:
(A)

(B)
(C)

(D)

(E)

(F)

Q.13. Write commands to perform following operations on two 4 x 4


ndarrays namely P and Q:

Create two hypothetical arrays for P and Q.

(A) Adding 10 to P
(B) Multiplication of the two array P and Q
(C) Divide all elements of Q by 7
(D) Round all the elements of Q to nearest integers
(E) Calculate remainder of all the elements of P when divided by 7
(F) Calculate square root of the elements of Q

ANSWER:
Creating arrays P and Q:

OUTPUT:
(A)
(B)

(C)

(D)

(E)

(F)

Q.14. Create an array x in the range 1 to 10 with values 0.1 apart. Create
another two arrays namely a and b as cos and sin of the elements of x.

ANSWER:
import matplotlib.pyplot as plt

import numpy as np
x=np.arange(0,10,0.1)

a=np.cos(x)

b=np.sin(x)
plt.scatter(x,b, c="b", marker="+")

plt.scatter(x,a, c="r", marker="x")

plt.savefig("scatter1.pdf")

plt.show()

OUTPUT:

Q.15. Create a comparative bar diagram between two arrays.


ANSWER:
import matplotlib.pyplot as plt
import numpy as np

overs=np.array ([1, 2, 3, 4, 5])


ind=np.array([13, 4, 16, 5, 7])

nz=np.array([3, 5, 4, 8, 11])

plt.bar(overs,ind, width=0.25, color="c", label="INDIA")


plt.bar(overs+0.25,nz, width=0.25, color="k", label="NEWZEALAND")

plt.xlabel("Overs")

plt.ylabel("Runs")

plt.xlim(0,6)

plt.ylim(0,18)
plt.title("IND Vs NZ")
plt.legend(loc="upper right")

plt.savefig("scatter.pdf")

plt.show()

OUTPUT:

Q.16. Create a Line Diagram of the following lists, overs[1,2,3,4,5] and


runs[15,5,6,10,8].
ANSWER:
import matplotlib.pyplot as plt
import pandas as pd

overs=[1,2,3,4,5]

runs=[15,5,6,10,8]
plt.xlabel("Overs")

plt.ylabel("Runs")

plt.plot(overs,runs, "k",lw=3, ls="solid", marker="x", markersize=10,


markeredgecolor="red")
plt.savefig("linediagram.pdf")

plt.show ()

OUTPUT:
Q.17. Given the following set of data:
Weight measurements for 16 small orders of French Fries (in grams).
78 72 69 81 63 67 65 75

79 74 71 83 71 79 80 69

(A) Create a simple histogram from the above data.

(B) Create a horizontal histogram from the above data.

(C) Create a step type of histogram from the above data.

(D) Create a cumulative histogram from the above data.

ANSWER:
(A)

import matplotlib.pyplot as plt

import pandas as pd
import numpy as np

ary=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69])
plt.hist(ary, bins=20)
plt.show()
(B)

import matplotlib.pyplot as plt


import pandas as pd

import numpy as np

ary=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69])
plt.hist(ary, bins=20, orientation="horizontal")

plt.show()

OUTPUT:

(C)

import matplotlib.pyplot as plt


import pandas as pd

import numpy as np

ary=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69])

plt.hist(ary, bins=20, histtype="step")

plt.show()
OUTPUT:

(D)
import matplotlib.pyplot as plt
import pandas as pd

import numpy as np

ary=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69])

plt.hist(ary, bins=20, cumulative=True)


plt.show()

OUTPUT:
Q.18. From the following ordered set of data
63, 65, 67, 69, 71, 71, 72, 74, 75, 78, 79, 79, 80, 81, 83

(A) Create a horizontal boxplot.


(B) Create a vertical boxplot.
(C) Show means in the boxplot.
(D) Create boxplot without a box.

ANSWER:

(A)
import matplotlib.pyplot as plt

import pandas as pd

import numpy as np
ary=np.array([63,65,67,69,71,71,72,74,75,78,79,79,80,81,83])

plt.boxplot(ary, vert=False)

plt.show()
OUTPUT:

(B)

import matplotlib.pyplot as plt


import pandas as pd

import numpy as np

ary=np.array([63,65,67,69,71,71,72,74,75,78,79,79,80,81,83])

plt.boxplot(ary, vert=True)

plt.show()

OUTPUT:
(C)
import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

ary=np.array([63,65,67,69,71,71,72,74,75,78,79,79,80,81,83])

plt.boxplot(ary, showmeans=True)

plt.show()

OUTPUT:
(D)

import matplotlib.pyplot as plt

import pandas as pd
import numpy as np

ary=np.array([63,65,67,69,71,71,72,74,75,78,79,79,80,81,83])

plt.boxplot(ary, showbox=False)

plt.show()

OUTPUT:
Q.21. Design a Python application to obtain a search criteria from user and
then fetch records based on that from empl table.

ANSWER:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
password="admin123", database="prerna")

mycursor=mydb.cursor()

deptno=int(input("Enter deptno to search"))


sql="select * from empl where deptno={}".format(deptno)
mycursor.execute(sql)

data=mycursor.fetchall()

for x in data:

print(x)

OUTPUT:
Q.19. Design a python application that fetches all the records from pet
table of menagerie database.

ANSWER:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
password="admin123", database="menagerie")
mycursor=mydb.cursor()

mycursor.execute("select * from pet")

data=mycursor.fetchall()
for x in data:

print(x)

OUTPUT:
Q.20. Design a Python application that fetches only those records from
Event table of Menagerie database where type is Kennel.

ANSWER:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
password="admin123", database="menagerie")

mycursor=mydb.cursor()

mycursor.execute("select * from event where type='kennel'")

data=mycursor.fetchall()

for x in data:
print(x)

OUTPUT:
Q.22. Design a Python application to insert a record into fields person id
and last name of staff table.

ANSWER:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
password="admin123", database="esha")

mycursor=mydb.cursor()
pid=int(input("Enter required person id"))

lname=input("Enter required lastname")

mycursor.execute("insert into staff (pid, lname) values({}, '{}')".format(pid,


lname))
mydb.commit()

mydb.close()

OUTPUT:
After inserting the records:
Q.23. Activate
(a) Write commands to create a Django project namely ‘classxii’ having two
apps in it namely list and order.
(b) Register these apps with the project.
(c) Create a templates folder in the base directory of your project.

(d) Register the templates folder created, with the project.

(e) The list app intends to show list of items available. For this, it has an html
page that displays a list of the items as shown below:

ITEMS LIST
1. Bath tubs 7. Bituminous Paints
2. Battery Charger 8. Blotting Paper
3. Battery Eliminator 9. Bolts and Nuts
4. Beam Scale(upto 1.5 tons) 10. Bolts Sliding
5. Belt leather and straps 11. Bone Meal
6. Brass Wire 12. Boot Polish

Create an html file namely list.html for this and store it under templates
folder of yours project.
(f) The order app intends to displays a form as shown below:

Customer name:
Phone Number:
Address:

Item To Be Ordered:
Order Quantity:

Create an html file namely order.html that displays this form and store it in
the templates folder.

(g) Create a view function for student app that renders

(h) Create a view function for order app that renders Add POST request
processing to it so that it stores the received from data in a csv file.
(i) In the urls.py file of yours project’s web- application folder (inner project
name folder),import the apps’ views.py modules by adding following import
commands.

ANSWER:
Creating the django project:
1. In the active virtual environment, type the following command in front
of the prompt:
django - admin startproject classxii
2. It will create a folder by the name classxii.
3. Now change to this folder, your project’s folder, using command CD,
i.e., give command:
cd classxii
4. Now type following command in front of the prompt to run the built-in
webserver:
python manage.py runserver
5. Finally, open your web browser window and type either of the
following commands in the address bar:
localhost:8000
127.0.0.1:8000
This would result in a web page showing the django has been installed
and is successfully running.
Creating app of the Django project:

Create the app with the following command:


python manage.py startapp student

Register app with the project after creating them:

Register the app to that django recognizes then as a part of the web
application.

For this open inner classxii folder’s setting.py file in any editor and add
your apps’ name (in string form) in INSTALLED_APPS list without
deleting any other setting.

Creating templates:

In the BASE DIRECTORY (outer project name folder i.e., classxii) create
a folder by the name templates.

Creating HTML file:


(i) Creating the HTML file named item1 connected to other two
HTML files namely item2 and item3.

HTML File – item1


<html>
<body>

<h1><b>ITEMS</b></h1><br>
<h3>Select the items you want to buy</h3><br>

<table style="width:30%">

<tr>
<th>ITEM NO</th>

<th>ITEM NAME</th>

<th>PRICE</th>

</tr>

<tr>
<td>I01</td>
<td>Bath Tubs</td>

<td>1000</td>

</tr>

<tr>
<td>I02</td>
<td>Battery Charger</td>

<td>500</td>

</tr>

<tr>

<td>I03</td>

<td>Battery Eliminator</td>

<td>2000</td>
</tr>
<tr>
<td>I04</td>

<td>Beam Scales(upto 1.5 tons)</td>


<td>1000</td>

</tr>

<tr>
<td>I05</td>

<td>Belt Leather & Straps</td>

<td>2500</td>

</tr>

<tr>
<td>I06</td>
<td>Brass Wire</td>

<td>1000</td>

</tr>

<tr>
<td>I07</td>
<td>Bituminous Paints</td>

<td>2300</td>

</tr>

<tr>

<td>I08</td>

<td>Blotting Paper</td>

<td>3000</td>
</tr>
<tr>
<td>I09</td>

<td>Bolts & Nuts</td>


<td>500</td>

</tr>

<tr>
<td>I10</td>

<td>Bolts Sliding</td>

<td>900</td>

</tr>

<tr>
<td>I11</td>
<td>Bone Meal</td>

<td>800</td>

</tr>

<tr>
<td>I12</td>
<td>Boot Polish</td>

<td>400</td>

</tr>

</table>

<a href="http://127.0.01:8000/two">PLACE ORDER</a>

</body>

</html>
The HTML File - item1 is connected to the HTML File - item2 through the link
displayed as “PLACE ORDER”.
HTML File – item2

<html>
<body>

<FORM action="#" method="POST">

{% csrf_token %}
Customer Name: <input type="text" name="custname"> <br>

Phone Number: <input type="text" name="phoneno"> <br>

Address: <input type="text" name="add"> <br>

Item To Be Ordered: <input type="text" name="orderitem"> <br>

Ordered Quantity: <input type="text" name="orderqty"> <br>


<input type="submit" value="SUBMIT">
<a href="http://127.0.01:8000/three">CHECK YOUR ORDER’S PLACEMENT
STATUS </a>

</FORM>

</body>
</html>
The HTML File - item2 is connected to other HTML File - item3 through a link
displaying the placed order have been successfully accepted.

HTML File – item3

<html>

<body>

<h1 align=center> CONGRATULATIONS! YOUR ORDER HAS BEEN PLACED


TIMELY. </h1>
<h1 align=center> THANKYOU FOR VISITING US! </h1>
</body>

</html>

Here, creating HTML Files comes to end, now it is needed to be saved in the
desired place so that it results in desired output.

(ii) Next is to store these HTML Files by saving those HTMLs


(which are to be displayed in response to a URL) in this
templates folder.

(iii) Next is to open the settings.py of the project (inner project


name folder) and add the name of templates folder (in string
form, i.e., in quotation marks) in the DIRS setting under
TEMPLATES.

The DIRS key of TEMPLATES setting specifies the place where


the server will look for templates while displaying webpages
of the web application.
Creating Views:

Next thing is to create views. Views receive the request in form of URL
and provide response in form of templates which are then presented
on the web browser.The views.py file of the app (in app directory),
where is to write view functions - one view function for each html page.
def <viewname> (request):
return render (request, <htmlfilenamestring>)
Creating URL Confs:
Once the template and views are ready, it is needed to link all these
with URLs through URL Confs. This process is also called URL routing

For defining URL configurations for the web application project, it is


needed to go to urls.py file of your inner project folder (the web
application folder) and do the following:

(i) Import view.py file of your apps where it is created the


view functions for the apps
from student import views
(ii) To define URL Conf for your defined views you need to
add following line given in the image below to URL
patterns list in the urls.py file.
Run Built-In Webserver:
manage.py runserver

Run the project:


HTTP GET REQUEST PROCESSING

Now in the web browser give URL as

localhost:8000/first/

This would be further linked to the other pages of the project.

Type the above code for running the first page of the project as given below:

The code input would result the first page that is the image given below:
The first page would be linked to the second page showing the image below
as for getting the information to store:

The second page would take the input and provide a link that specifies the
placed order is successfully accepted.
The input took in the second page would be stored in the csv connected and
coded in the views.

You might also like