You are on page 1of 35

EXNO:1 PROGRAM USING ELEMENTARY DATA ITEMS , LISTS ,

DICTIONARIES AND CONDITIONAL BRANCHES ,LOOPS.

AIM:
To develop the python program for elementary data items, list, dictionaries
and conditional statement and loops.

PROCEDURE:

Step1: Start the program.

Step2: Create the list and enter the Number of data elements in the list.

Step3: Using for loop enter the data elements.

Step4: Input the number to be Searched to chech whether it is present in


the list or not.

Step5: Display the location of the elements if present.

Step6: Stop the program


Coding:
a)LIST
list1=[]
print("Enter the count of list: ")
maxi=int(input())
print("Enter the list of numbers: ")
for i in range(0,maxi):
n=int(input())
list1.append(n)
num=int(input("Enter the number to be searched: "))
pos=-1
for i in range (0,len(list1)):
if list1[i]==num:
pos=i+1
if pos==-1:
print(num,"is not present in the list")
else:
print(num,"is present in the list at",pos,"position")
OUTPUT:
B)Dictionary

PROCEDURE:

Step1: Start the program.

Step2: Create a Dictionary with key and value pass.

Step3: User for loop perform the following System.

Step4: Convert the Corresponding value of the key.

Step5: Find the corresponding value of the key.

Step6: Concatenate the values and print the result.

Step7: Stop the program.


Coding:
num=input("enter any number:")
numberNames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven',
8:'Eight',9:'Nine'}
result=' '
for ch in num:
key=int(ch)
value=numberNames[key]
result=result+' '+value
print("The number is:",num)
print("The numberName is:",result)
OUTPUT:

RESULT:
Thus the program is executed and verified Succesfully
EXNO:2 PROGRAM USING FUNCTIONS

AIM:
To Develop a python program using function.

PROCEDURE:

Step1 : Start the program.

Step2 : Define the functions add(),subtract(),multiply(),divide().

Step3 : Enter the choice for selecting the functions.

Step4 : Perform the function and display the result.

Step5 : Stop the program.


CODING:
def add(p,q):
return p+q
def subtract (p,q):
return p-q
def multiply(p,q):
return p*q
def divide(p,q):
return p/q
print("Please select the operation:")
print("a.ADD")
print("b.SUBTRACT")
print("c.MULTIPLY")
print("d.DIVIDE")
choice=input("please enter choice(a/b/c/d):")
num1=int(input("please enter the first number:"))
num2=int(input("please enter the second number:"))
if choice=='a':
print(num1,"+",num2,"=",add(num1,num2))
elif choice=='b':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice=='c':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice=='d':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("This is an invalid input")
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO:3 PROGRAM USING EXCEPTION HANDLING

AIM:
To Develop a python program using function.

PROCEDURE:
Step1: Start the program.

Step2:Enter the alphabet to be checked.

Step3:Using if else statement check the condition.

Step4:If the given value is less than the alphabet value, raise the Exception
“InputTooSmallError”.

Step5:If the given value is greater than the alphabet value, raise the Exception
“InputTooLargeError”.

Step6:The given alphabet value is equal to the alphabet value ,display the
statement “congratulation ! you guessed it correctly” .

Step7: Stop the Process.


CODING:
class Error(Exception):
"""Base class for other exceptions"""
pass
class InputTooSmallError(Error):
"""Raised when the entered alphabet is smaller than actual one"""
pass
class InputTooLargeError(Error):
"""Raised when the entered alphabet is larger than actual one"""
pass
alphabet='m'
while True:
try:
apb = input("Enter an alphabet: ")
if apb < alphabet:
raise InputTooSmallError
elif apb > alphabet:
raise InputTooLargeError
break
except InputTooSmallError:
print("The entered alphabet is too small, try again!")
print('')
except InputTooLargeError:
print("The entered alphabet is too large, try again")
print('')
print("Congratulations! You guessed it correctly.")
OUTPUT:

RESULT:
Thus the program is executed and verified successfully
EX.NO:4 PROGRAM USING CLASSES AND OBJECTS
AIM:
To Develop a python program using classes and objects.

PROCEDURE:

Step1: Start the Program.

Step2: Create a super class named “BookStore”

Step3: Define a class init function with argument necessary for bookstore class.

Step4: Define ‘bookinfo’ function.Using this function display


the book title and author.

Step5: Create the objects for class ‘bookstore; as b1,b2,b3.

Step6: Using the objects call the bookinfo() function

Step7: Display the total numbers of books.

Step8: stop the program.


CODING:
class BookStore:
noofbooks=0
def __init__(self,title,author):
self.title=title
self.author=author
BookStore.noofbooks+=1
def bookinfo(self):
print("book Title:" ,self.title)
print("Book Author:",self.author,"\n")
b1 = BookStore("Great Exceptions","Charles dickens")
b2 = BookStore("war and peace","leo tolstoy")
b3 = BookStore("middlemarch","george eliot")

b1.bookinfo()
b2.bookinfo()
b3.bookinfo()
print("BookStore.noofbooks:",BookStore.noofbooks)
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO: 5 PROGRAM USING INHERITANCE

AIM:
To Develop a python program using inheritance.

PROCEDURE:

Step1: Start the Program.

Step2: Create a super class named “SHAPES”

Step3: Define the function init, takesides() and discsides()

Step4: Create a Subclass named ‘rec’ to derive the methods from the base class
‘SHAPES’

Step5: Define the method named ‘FIND AREA’ to calculate area of the Rectangle.

Step6: Create the object for the class rec()

Step7: Using the object call the methods

Step8: Display the result.

Step9: stop the program.


CODING:
class car:
def __init__(self,model,capacity,variant):
self.__model = model
self.__capacity = capacity
self.__variant = variant
def getmodel(self):
return self.__model

def getcapacity(self):
return self.__capacity

def setcapacity(self,capacity):
self.__capacity=capacity

def getvariant(self):
return self.__variant

def setvariant(self,variant):
self.__variant=variant

class vehicle(car):
def __init__(self,model,capacity,variant,color):
super().__init__(model,capacity,variant)
self.__color = color

def vehicleinfo(self):
return self.getmodel()+" "+self.getvariant()+" in" +self.__color+ "with"+
self.getcapacity()+ "seats"

v1 = vehicle("i20 active","4","SX","Bronze")
print(v1.vehicleinfo())
print(v1.getmodel())
v2 = vehicle("fortuner","7","MT2755","white")
print(v2.vehicleinfo())
print(v2.getmodel())
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO: 6 PROGRAM USING POLYMORPHISM

AIM:
To Develop a python program using polymorphism.
PROCEDURE:

Step1: Start the Program.

Step2: Create a classes named “parrot” , ”Penguin”.

Step3: Each of the classes have method fly() and swim().

Step4:Create a common interface flying_test() function.

Step5: Create a object for classes parrot as blu and penguin as peggy.

Step6: Perform the function and display the result.

Step7:Stop the program.


CODING:
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")

def flying_test(bird):
bird.fly()

blu = Parrot()
peggy = Penguin()
flying_test(blu)
flying_test(peggy)
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO: 7 PROGRAM TO IMPLEMENT FILE OPERATION

AIM:
To Develop a python program to implement file operation.
PROCEDURE:

Step1: Start the Program.

Step2: Create a file named ‘app.log’.

Step3: Write the line in the file.

Step4: open the app.log file in read mode.

Step5: Using read() function to read the data in the file.

Step6: Using the tell() function ,disply the current file position.

Step7: Using the read() function again read the data and display the data.

Step8: Close the file.

Step9: Stop the program


CODING:
with open('file.txt', 'w', encoding = 'utf-8') as f:
f.write('It is my first file')
f.write('This file')
f.write('contains three lines')
f = open('file.txt', 'r+')
data = f.read(19);
print('Read String is : ', data)
position = f.tell();
print('Current file position : ', position)
position = f.seek(0, 0);
data = f.read(19);
print('Again read String is : ', data)
f.close()
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO: 8 PROGRAM USING MODULES
AIM:
To Develop a python program using modules.

PROCEDURE:

Step1: Start the Program.

Step2: Enter the number for calculating the factorial value.

Step3: If the number is negative ,display the message “Sorry,Factorial does not
exist for negative number.

Step4: If the number is zero ,display the message “the Factorial of 0 is 1”.

Step5: If the number is greater than one calculate the factorial value and display
the result.

Step6: Stop the program.


CODING:
num=int(input("Enter a number:"))
factorial=1
if num<0:
print("Sorry,factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("the factorial of",num,"is",factorial)
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
EX.NO : 9 PROGRAMS FOR CREATING DYNAMIC AND INTERACTIVE
WEB PAGES USING FORMS.
AIM:
To write a program for creating dynamic and interactive web pages using forms
in Python.
Procedure and Coding:
Python Flask: Make Web Apps with Python
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField,
SubmitField

# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'

class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])

@app.route("/", methods=['GET', 'POST'])


def hello():
form = ReusableForm(request.form)

print form.errors
if request.method == 'POST':
name=request.form['name']
print name
if form.validate():
# Save the comment here.
flash('Hello ' + name)
else:
flash('All the form fields are required. ')

return render_template('hello.html', form=form)


if __name__ == "__main__":
app.run()
We then line_number:false create the template hello.html in the /templates/
directory:

<title>Reusable Form Demo</title>


{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{ { message[1] }}</li>
{% endfor %}</ul>
{% endif %}
{% endwith %}
<form action="" method="post">
&#123; &#123; form.csrf &#125;&#125;
<div class="input text">
{ { form.name.label }} { { form.name }}</div>
<div class="input submit">
<input type="submit" value="Submit"></div>
</form>
Start the application and open it in your webbrowser at
http://127.0.0.1:5000.
python miniapp.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader

If you will submit an empty form, you will get an error. But if you enter your
name, it will greet you. Form validation is handled by the wtforms module,
but because we gave the argument name = TextField('Name:',
validators=[validators.required()])
OUTPUT:

RESULT:
Thus the program is executed and verified successfully.
Ex.No : 10 Program using database connection and web services

AIM:
To write a Program using database connection and web services in Python.

Procedure and Coding:

Install SQLite:
Use this command to install SQLite:

$ sudo apt-get install sqlite


Verify if it is correctly installed. Copy this program and save it as test1.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite


import sys con = None
try:
con = lite.connect('test.db')
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print "SQLite version: %s" % data
except lite.Error, e:
print "Error %s:" % e.args[0] sys.exit(1)
finally:
if con:
con.close()

Execute with:
$ python test1.py

It should output:
SQLite version: 3.8.2

The script connected to a new database called test.db with this line:
con = lite.connect('test.db')
It then queries the database management system with the command
SELECT SQLITE_VERSION()

which in turn returned its version number. That line is known as an SQL query:

SQL Create and Insert


The script below will store data into a new database called user.db
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite


import sys
con = lite.connect('user.db')

with con:
cur = con.cursor()
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")

SQLite is a database management system that uses tables. These tables can
have relations with other tables: it’s called relational database management
system or RDBMS. The table defines the structure of the data and can hold the
data. A database can hold many different tables. The table gets created using
the command:

cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")

We add records into the table with these commands:


cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")

SQLite query data


We can explore the database using two methods: the command line and a
graphical interface.
From console: To explore using the command line type these commands:
sqlite3 user.db .tables
SELECT * FROM Users;

This will output the data in the table Users.


sqlite&gt; SELECT * FROM Users;
1|Michelle
2|Sonya
3|Greg

From GUI: If you want to use a GUI instead, there is a lot of choice. Personally
I picked sqllite-man but there are many others. We install using:
sudo apt-get install sqliteman
We start the application sqliteman. A gui pops up.
se those queries in a Python program:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
con = lite.connect('user.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Users")
rows = cur.fetchall()
for row in rows:
print row
This will output all data in the Users table from the database
$ python get.py
(1, u'Michelle')
(2, u'Sonya')
(3, u'Greg')
Creating a user information database
We can structure our data across multiple tables. This keeps our data
structured, fast and organized. If we would have a single table to store
everything, we would quickly have a big chaotic mess. What we will do is
create multiple tables and use them in a combination. We create two tables:
import sqlite3 as lite
import sys
con = lite.connect('system.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
cur.execute("INSERT INTO Users VALUES(2,'Howard')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")
cur.execute("CREATE TABLE Jobs(Id INT, Uid INT, Profession TEXT)")
cur.execute("INSERT INTO Jobs VALUES(1,1,'Scientist')")
cur.execute("INSERT INTO Jobs VALUES(2,2,'Marketeer')")
cur.execute("INSERT INTO Jobs VALUES(3,3,'Developer')")
The jobs table has an extra parameter, Uid. We use that to connect the two
tables in an SQL query:
SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON
users.ID = jobs.uid
You can incorporate that SQL query in a Python script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys con = lite.connect('system.db')
with con:
cur = con.cursor()
cur.execute("SELECT users.name, jobs.profession FROM jobs INNER JOIN
users ON users.ID = jobs.uid")
rows = cur.fetchall()
for row in rows:
print row

output:

$ python get2.py
(u'Michelle', u'Scientist')
(u'Howard', u'Marketeer')
(u'Greg', u'Developer')

RESULT:
Thus the program is executed and verified successfully.

You might also like