Gauri Project
Gauri Project
Agenda
Day -1 (Phase -1)
List
Tuples
Dictionary
Function
Modules
CGI Programming
Brush-up
up your database concept
Query Session
Our Mission:
Features of Python:-
Platform independent
Open Source
Object Oriented
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
First of all install the Python 2.7.12 on your system. After installation it will create a
directory in C: drive named Python27. In Python27 there is a file python.exe. Copy the path
of python.exe from address bar.
Open the command prompt, type python and press enter key.
The python prompt will open. Now type the following code:
code:-
Hello Python!
Now type notepad SimpleCalc.py. The notepad editor will open and type the following code:-
code:
Now at command prompt type python SimpleCalc.py it display the following output:-
output:
Summation = 15
Subtraction = 5
Multiplication = 50
Division = 2
if condition:
Statement 1
Statement 2
else:
Develop a program in Pythonhon to calculate bill after taking units from user. Take the
following logic to calculate the electricity bill;
For 1 to 150 units rate is Rs. 2.40, for next 150 (150 to 300) units rate is Rs. 3.00 and
Rs. 3.20 for units above 300.
if unit<=150:
bill=unit*2.40
bill=(150*2.40)+(unit-150)*3
150)*3
else:
bill=(150*2.40)+(150*3)+(unit
bill=(150*2.40)+(150*3)+(unit-300)*3.20
while loop:- The while is a keyword in python which works as loop control. The syntax of
while loop is given below:-
while condition:
Statement 1
Statement 2
import time
i=10
while i>0:
print i
time.sleep(1)
i=i-1
The above code will display the numbers from 10 to 1 in interval of 1 second.
sum=0
while n>0:
r=n%10
sum=sum+r
n=n/10
Output:
Sum of digits : 6
n=input(“Enter a number : ”)
rev=0
while n>0:
r=n%10
rev=rev*10+r
n=n/10
n=input(“Enter a number : ”)
c=0
i=1
while i<=n:
ifn%i==0:
c=c+1
i=i+1
if c==2:
else
for loop:- The for is a keyword which work as loop control. Basically, the for loop in python
work like foreach loop in java or C#. It is used for traversing of a sequence. Some examples
example
using for loop are given below:-
str=”PYTHON”
for c in str:
print c
Output:
The list is a most versatile datatype available in Python which can be written as a list of
comma-separated
separated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type.
For example:-
list1=[“Rohit”,”Mohit”,”Shobhit”,”Mudit”]
list2=[10,20,30,40,50]
list3=[“a”,”e”,”i”,”o”,”u”]
Write a program in python to make a list and traverse the elements of list.
names=[“Rohit”,”Satyam”,”Brijesh”]
print element
Output:
Rohit
Satyam
Brijesh
list=[]
i=0
while i<10:
list.insert(i,item)
i=i+1
Write a program in python to create a list of students by taking input from user. Now
display the names of students in ascending and descending order.
names=[]
print “Enter”,n,”names”
i=0
while i<n:
element=raw_input();
names.insert(i,element)
i=i+1
names.sort()
print element
names.reverse()
print element
Tuple in Python
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.
For example:
tup2 = (1, 2, 3, 4, 5 )
tup1 = ()
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
Dictionary in Python
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written
with just two curly braces, like this: {}.
For example:-
Function in Python
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
co
reusing.
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ) .
• Any input parameters or arguments should be placed within these parentheses. You
can also
so define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement
ent return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
deffunctionname( parameters ):
"function_docstring"
function_suite
return [expression]
def greatest(a,b):
if(a>b):
return a
else:
return b
g=greatest(x,y)
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
f=fact(x)
Modules in Python
A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use. A module is a Python object with arbitrarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
def add(a,b):
return (a+b)
def sub(a,b):
return (a-b)
defmult(a,b):
return (a*b)
def div(a,b):
return (a/b)
importMyCalc
Make a module TempConv.py with two methods ctof() and ftoc() to convert temperature from
centigrade to forenhite and forenhite to centigrade.
defctof(c):
f=(9*c)/5+32
return f
defftoc(f):
c=(f-32)*5/9
return c
importTempConv
ch=input()
if(ch==1):
f=TempConv.ctof(c)
elif (ch==2):
c=TempConv.ftoc(f)
else:
CGI Programming
What is CGI?
• The Common Gateway Interface, or CGI, is a standard for external gateway programs
to interface with information servers such as HTTP servers.
• The current version
on is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link to
browse a particular web page or URL.
• Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
• Web Server parses the URL and looks for the filename. If it finds that file then sends
it back to the browser, otherwise sends an error message indicating that you requested
a wrong file.
• Web browser takes response from web server and display
displayss either the received file or
error message.
#!/usr/bin/python
print "Content-type:text/html\r\n\\r\n"
print “<html>”
print “<head>”
print “</head>”
print “<body>”
print “</body>”
print “</html>”
You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your CGI Program. Most frequently, browser
uses two methods two pass this information to we
webb server. These methods are GET Method
and POST Method.
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ?character as follows:
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
bin/hello.py?key1=value1&key2=value2
Here is a simple URL, which passes two values to hello_get.py program using GET method.
/cgi-bin/hello_get.py?first_name=Brijesh&last_name=Mishra
bin/hello_get.py?first_name=Brijesh&last_name=Mishra
#!/usr/bin/python
importcgi, cgitb
form = cgi.FieldStorage()
first_name = form.getvalue('first_name')
last_name =form.getvalue('last_name')
print "Content-type:text/html\r\n\\r\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
print "</body>"
print "</html>"
Output:
This example passes two values using HTML FORM and submit button. We use same CGI
script hello_get.py to handle this input.
<form action="/cgi-bin/hello_get.py"
bin/hello_get.py" method="get">
</form>
A generally more
ore reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ?in the URL it sends it as a separate message. This
message
sage comes into the CGI script in the form of the standard input.
Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python
importcgi, cgitb
form = cgi.FieldStorage()
first_name = form.getvalue('first_name')
last_name =form.getvalue('last_name')
print "Content-type:text/html\r\n\\r\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
print "</body>"
print "</html>"
<form action="/cgi-bin/hello_get.py"
bin/hello_get.py" method="post">
</form>
You can choose the right database for your application. Python Database API supports a wide
range of database servers such as:
• GadFly
• mSQL
• MySQL
• PostgreSQL
• Microsoft SQL Server 2008
• Informix
• Interbase
• Oracle
• Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs
.You must download a separate DB API module for each database you need to access. For
example, if you need to access an Oracle database as well as a MySQL database, you must
download both the Oracle and the MySQL database modules.
The DB API provides a minimal standard for working with databases using Python structures
and syntax
ax wherever possible. This API includes the following:
We would learn all the concepts using MySQL, so let us talk about MySQLdb module.
importMySQLdb
Database Connection:
Example:
#!/usr/bin/python
importMySQLdb
db = MySQLdb.connect("127.0.0.1
MySQLdb.connect("127.0.0.1","testuser","test123","TESTDB" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
db.close()
If a connection is established with the datasource, then a Connection Object is returned and
saved into db for further use, otherwise db is set to None. Next, db object is used to create a
cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it
ensures that database connection is closed and resources are released.
#!/usr/bin/python
importMySQLdb
db = MySQLdb.connect("127.0.0.1
MySQLdb.connect("127.0.0.1","testuser","test123","TESTDB" )
cursor = db.cursor()
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
cursor.execute(sql)
db.close()
INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example executes SQL INSERT statement to create a record into EMPLOYEE
table:
#!/usr/bin/python
db = MySQLdb.connect("127.0.0.1
MySQLdb.connect("127.0.0.1","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
READ Operation
READ Operation on any database means to fetch some useful information from the database.
Once our database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch single record or fetchall() method to
fetch multiple values from a database table.
• fetchone(): It fetches the next row of a query result set. A result set is an object that is
returned when a cursor obj object is used to query a table.
• fetchall(): It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining
remaining rows from the result set.
• rowcount: This is a read-onlyonly attribute and returns the number of rows that were
affected by an execute() method.
#!/usr/bin/python
importMySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
ws in a list of lists.
# Fetch all the rows
results = cursor.fetchall()
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
except:
db.close()
Python Questionnaire
Q.1 Develop a program using Python to calculate volume and surface area of cuboid.
x2=(-b-math.sqrt(b*b-4*a*c))/(2*a)
4*a*c))/(2*a)
Q.3 Write a Python program to convert given number of days to a measure of time given in
years, weeks and days. For example 375 days is equal to 1 year 1 week and 3 days (ignore
leap year).
Q.4 Write a Python program to convert the given binary number into decimal.
Q.5 Develop a program in Python to calculate bill after taking units from user. Take the
following
lowing logic to calculate the electricity bill;
For 1 to 150 units rate is Rs. 2.40, for next 150 (150 to 300) units rate is Rs. 3.00 and Rs.
3.20 for units above 300.
Q.8 Develop a program in Python to generate Fibonacci sequence up to n terms where the
value of n is entered by user.
Q.10 Develop a list in Python store five names in list and sort the names in ascending and
descending order.
Q.11 Develop a list in Python store ten numbers in this list. Now take a number
number as input and
search the given number in list.
Q.12 Develop a program using Python to take full name as input and display the short name.
E.g. Ajay Pratap Singh as A.P.Singh
Q.13 Develop a program in Python to check the given string is Palindrome or not.
Q.14 Develop a program in Python to take a string as input. Find a substring and replace the
given string with another string. Use replace function to do this.
Q.16 Develop a module TempConv having two functions CtoF() which convert temperature
from centigradeto forenhite and FtoC() which converttemperature ffromforenhite
romforenhite to
centigrade. Test the given module.
Q.17 Design
gn a module to represent a bank account. Include the following members and
methods:-
Data Members
ii.)Account Number
iii.)Type of Account
Methods
iii.)To
i.)To Withdraw an amount after checking balance.
iv.) To display the name and balance.
Q.19 Develop a program in Python to take as string as input and display all characters by
using for loop.
Q.20 Develop a program using Python to take two tuples tup1 and tup2. Now combine tuples
tup1, tup2 into another tuple tup3. Iterate the elements
element of tup3.
Q.21 Develop a web page using Python which show the following form to user and store the
data given by user in a table (Use MySql as backend).
Mobile
Address
Save
Q.22 Develop a Login page which ask user to enter his Login Id and Password and pressing
Login button it should check the validation of Login Id and Password from database and
display a Welcome page if user is valid user and display error message on login page itself if
user is invalid.
Q.23 Develop a webpage using Python to ask user name and after click on submit button the
name should be displayed on another web page. (Use the concept of session).
Q.25 Develop a web application using Python which can generate the given number of
recharge voucher code in the following format:
format:-
2394-5341-3412-9145
Q.26 Develop a Web Application which can display the result of a student on entering the
RollNo on following manner:-
First Page:
GO
Second Page:
You have design the database to hold the above information yourself with reasonable column
types and size.
Q.27 Develop a webpage using Python to perform simple arithmetic operations addition,
subtraction, multiplication and division of two numbers.
Q.28
.28 Develop a function which returns character represented by a ASCII number.
Q.29 Develop a program using Python to take date of birth as input and display the age on
current date in years, months and days.
Q.30 Develop a program using Python to take date of birth as input and find the Lucky
number. The lucky no. will be sum of all digits of date of birth and it must be a single digit.
Based on calculated Lucky no. predict the future.
Connections: Use the PIN 33, 35, 37 as the GPIO output pins of the raspberry pi for Green Bulb, Red
Bulb, Buzzer.
A User will play a game of arithmetic calculations. Here user will enter two numbers (NUM1) &
(NUM2) and will enter the result There are two bulbs in the arrangement (RED and GREEN). For
each correct answer Green bulb should blink and the score of user should get incremented and printed
on the Python shell along with a message “Right Answer your score is __”. Similarly for the incorrect
answer the Red bulb should blink along with a buzzer indicating a wrong answer. The score should
get decremented and a message “Wrong Answer your score is __” should be displayed.
Connections: Take a PIR Sensor and attach its output on PIN 37 of Raspberry Pi. Take an LED and
attach it on PIN35 of the Raspberry Pi.
Objective: The object is to identify presence of any trespasser near your door. If PIR sensor detect an
object the LED should turn ON and OFF (5 times) and you should get a message “Tresspasser
Detected” on Python shell.
For any queries related to python or any other subject/technology, drop us a mail at
[email protected] or visit our website at www.softproindia.org
Thank,
Brijesh Mishra
Sr. Manager(IT)
Softpro India