Python two marks
Python two marks
COLLEGE OF ENGINEERING(Autonomous)
Department of Computer Science and Engineering
Subject Name: Programming in Python
Subject Code: 16CS667 Year/Semester: III/VI
Course Outcomes: On completion of this course, the student will be able to
CO1 Illustrate basic concepts of python programming.
CO2 Understand the concepts of functions and exceptions
CO3 Develop programs using modules and class
CO4 Store and retrieve data using file and databases.
CO5 Acquire knowledge in Web and GUI design
Program Outcomes (POs) and Program Specific Outcomes (PSOs)
A. Program Outcomes (POs)
Engineering Graduates will be able to :
Engineering knowledge: Ability to exhibit the knowledge of mathematics, science, engineering
PO1 fundamentals and programming skills to solve problems in computer science.
PO2 Problem analysis:Talenttoidentify, formulate, analyze and solve complex engineering
problems with the knowledge of computer science. .
PO3 Design/development of solutions: Capability to design, implement, and evaluate a computer
based system, process, component or program to meet desired needs.
PO4 Conduct investigations of complex problems:Potential to conduct investigation of complex
problems by methods that include appropriate experiments, analysis and synthesis of
information in order to reach valid conclusions.
PO5 Modern tool Usage:Ability to create, select, and apply appropriate techniques, resources and
modern engineering tools to solve complex engineering problems.
PO6 The engineer and society:Skill to acquire the broad education necessary to understand the
impact of engineering solutions on a global economic, environmental, social, political, ethical,
health and safety.
PO7 Environmental and sustainability: Ability to understand the impact of the professional
engineering solutions in societal and Environmental contexts and demonstrate the knowledge of,
and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibility and norms
of the engineering practices.
PO9 Individual and team work:Ability to function individually as well as on multi-disciplinary
teams.
PO10 Communication:Ability to communicate effectively in both verbal and written mode to excel
in the career.
PO11 Project management and finance:Ability to integrate the knowledge of engineering and
management principles to work as a member and leader in a team on diverse projects.
PO12 Life-long learning:Ability to recognize the need of technological change by independent and
life-long learning.
B. Program Specific Outcomes (PSOs)
PSO1 Technical Competency: Develop and Implement computer solutions that accomplish goals to
the industry, government or research by exploring new technologies.
PSO2 Professional Awareness: Grow intellectually and professionally in the chosen field.
2 David Beazley, Brian K. Jones, "Python Cookbook", O'Reilly Media, 3 Edition, 2013
rd
4 www.python.org
5 www.diveintopython3.net
Unit I
Part A
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit
on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
32. Explain while loop with example. Eg:
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff!'
More formally, here is the flow of execution for a while statement:
Evaluate the condition, yielding True or False.
If the condition is false, exit the while statement and continue execution at the next statement.
If the condition is true, execute the body and then go back to step 1
33. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for variable in sequence:
code block
Eg:
x=4
for i in range(0, x):
print i
Part B
STATEMENTS
3. What is the use of return statement?
Return gives back or replies to the caller of the function. The return statement causes our function
to exit and hand over back a value to its caller.
Eg:
def area(radius):
temp = math.pi * radius**2
return temp
4. What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Eg:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
5. Define Anonymous function?
Anonymous function is a function that is defined without a name. While
normal functions are defined using the def keyword, in Python anonymous
functions are defined using the lambda keyword. Hence, anonymous functionsare
also called lambda functions.
Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever
function objects are required.
double = lambda x: x * 2
# Output: 10
print(double(5))
7. Define Decorator.
A decorator is a function that takes one function as input and returns another function. add
@decorator_name before the function that you want to decorate.
8. Define Generator.
Generator functions allow you to declare a function that behaves like an iterator,
i.e. it can be used in a for loop.
Python provides generator functions as a convenient shortcut to building iterators
1 # a generator that yields items instead of returning a list
2 def firstn(n):
3 num = 0
4 while num < n:
5 yield num
6 num += 1
7
8 sum_of_first_n = sum(firstn(1000000))
The code within the try clause will be executed statement by statement.If an exception occurs, the
rest of the try block will be skipped and the except clause will be executed.
Syntax
try:
some statements here
except:
exception handling
Example
try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero, you're silly."
12. How do you handle the exception inside a program when you try to open a non-
existent file?
13. Write the syntax of Try ... except ... else clause.
The else clause in a try , except statement must follow all except clauses, and is useful for code that
must be executed if the try clause does not raise an exception.
try:
data = something_that_can_go_wrong
except IOError:
handle_the_exception_error
else:
doing_different_exception_handling
1. re.match()
2. re.search()
3. re.findall()
4. re.split()
5. re.sub()
6. re.compile()
17. Write a regular expression to check the validity of phone number.
import re
li=['9842710025','0000000900','99999x9999']
for val in li:
if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
print("yes")
else:
print("no")
18. What is the use of search method?
Scan through string looking for a location where the regular expression pattern produces a match,
and return a corresponding MatchObject instance. Return None if no position in the string matches
the pattern; note that this is different from finding a zero-length match at some point in the string.
import re
st="The rain and spain in plain"
r=re.search("spain",st)
if(r):
print("there is amatch")
else:
print("no match")
print(r.start())
print(r.end())
print(r.span())
Part B
1. Briefly discuss in detail about function prototyping in python. With suitable example program.
2. Describe the syntax and rules involved in the return statement in python
3. Describe in detail about lambda functions or anonymous function.
4. What type of parameter passing is used in Python? Explain with sample programs.
5. What are regular expressions? How to find whether an email id entered by user is valid or not using
Python‘re’ module.
6. Explain the use of try and catch block in python with its syntax. Also list the standard exceptions in
python.
7. Write short notes on decorators and generators.
Unit III
Part A
4. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Syntax: from <mypackage> import <modulename>
5. What is the use of dir function?
Python dir() function attempts to return a list of valid attributes for the given object. If no argument
provided, then it returns the list of names in the current local scope. If the module name is passed as
an argument this function returns the functions implemented in each module.
6. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called __init__.py
7. Define class.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
8. How to create object in python?
The procedure to create an object is similar to a function call.
>>> ob = MyClass()
This will create a new instance object named ob. We can access attributes of objects using the object
name prefix.
9. Define method overriding in python.
In Python method overriding occurs by simply defining in the child class a method with the same
name of a method in the parent class.
class Parent(object):
def __init__(self):
self.value = 4
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
>>> c.get_value()
3. Class methods
4. Static methods
13. What is Duck typing in Python?
Python is strongly but dynamically typed. This means names in code are bound to strongly typed
objects at runtime. The only condition on the type of object a name refers to is that it supports the
operations required for the particular object instances in the program. For example, I might have two
types Person and Car that both support operation "run", but Car also supports "refuel". So long as my
program only calls "run" on objects, it doesn't matter if they are Person or Car. This is called "duck
typing" after the expression "if it walks like a duck and talks like a duck, it's a duck."
Unit IV
Part A
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1,
line buffering is performed while accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the indicated buffer size. If negative, the
buffer size is the system default(default behavior).
The remove() method is used to delete the files by supplying the name of the file to be deleted
as argument.
Syntax: os.remove(filename)
Example:
{
"Name" : "Alex",
"City" : "Chennai",
"Country" : "India",
"Age" : 25,
"Skills" : [ "Java", "JSP"]
}
15. Write the steps to convert CSV into JSON format.
Get paths to both input csv file, output json file and json formatting via Command line
arguments
Read CSV file using Python CSV DictReader
Convert the csv data into JSON or Pretty print JSON if required
Part B
1. How to create a module and use it in a python program explain with an example.
2. List out the types of modules, and explain any of the two in deatil.
3. Write short notes on isinstance() and __init__()
4. Briefly discuss about python packages.
5. List the features and explain about different Object Oriented features supported by
Python.
6. How to declare a constructor method in python? Explain.
7. Explain the concept of method overriding with an example.
UNIT V
Part A
3. What are the main methods available for creating GUI application using of Tkinter?
a. To create a main window, tkinter offers a method ‘Tk(screenName=None,
baseName=None, className=’Tk’, useTk=1)’.
i. m=tkinter.Tk() where m is the name of the main window object
b. There is a method known by the name mainloop() is used when you are ready for the
application to run. mainloop() is an infinite loop used to run the application, wait for an
event to occur and process the event till the window is not closed.
i. m.mainloop()
Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
6. What are the geometry manager classes of Tkinter ?
widget.bind(event, handler)
If an event matching the event description occurs in the widget, the given handler is called with
an object describing the event.
root = Tk()
def callback(event):
print "clicked at", event.x, event.y
root.mainloop()
Socket programming is started by importing the socket library and making a simple socket.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter
is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family
ipv4. The SOCK_STREAM means connection oriented TCP protocol.
10. How emails are sent using python?
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing
e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which is used to send an e-mail −
import smtplib
a post query string doesn’t show up in the browser as part of the current URL
Part B
1. Explain about Tkinter and write python script for calculator.
2. Briefly explain the different widgets of Tkinter.
3. Describe about socket programming in python.
4. Write a python code for CGI programming.
5. Explain GET and POST method of CGI with an example.