Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Python two marks

Uploaded by

hod cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python two marks

Uploaded by

hod cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 21

K.S.R.

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.

DATE: 26.12.2018 COURSE FACULTY H.O.D PRINCIPAL


K.S.R. COLLEGE OF ENGINEERING (Autonomous) R 2016
SEMESTER - VI
PROGRAMMING IN PYTHON L T P C
16CS667
(ELECTIVE) 3 0 0 3
Prerequisite: Basic Knowledge of Object oriented programming(16CS346)
Objectives:
 To impart the fundamental concepts of python programming.
 To learn the basic of functions and exception.
 To learn to create programs using class.
 To study database system for storing and retrieving data.
 To learn the concept of Web and GUI design.
UNIT - I FUNDAMENTALS OF PYTHON [9]
Introduction to Python - Advantages of Python programming - Variables - I/O methods - Data types - Strings - List -
Tuples - Dictionaries - Sets Operators - Flow Control - Loops.
UNIT - II FUNCTIONS AND EXCEPTION [9]
Functions: Declaration - Types of arguments - Anonymous functions: Lambda - Generators - Decorators - Exception
Handling - Regular Expression - Calendars and Clocks.
UNIT - III MODULES AND CLASS [9]
Introduction - Modules and the import Statement - Packages - Objects and Classes: Class with class - Override a
Method - Get and Set Attribute Values - Name Mangling - Method Types - Duck Typing - Relationships.
UNIT - IV FILES AND DATA BASES [9]
File I/O operations - Directory Operations - Reading and Writing in Structured Files: CSV and JSON - Data manipulation
using Oracle, MySQL and SQLite.
UNIT - V GUI AND WEB [9]
UI design: Tkinter - Events - Socket Programming - Sending email - CGI: Introduction to CGI Programming, GET and
POST Methods, File Upload.
Total = 45 Periods
Course Outcomes: On Completion of this course , the student will be able to
 Illustrate basic concepts of python programming.
 Understand the concepts of functions and exceptions.
 Develop programs using modules and class.
 Store and retrieve data using file and databases.
 Acquire knowledge in Web and GUI design.
Text Book :
1 Bill Lubanovic, "Introducing Python Modern Computing in Simple Packages", O'Reilly Media, 1st Edition 2014
References :
1 Mark Lutz, “Learning Python”, O'Reilly Media, 5 Edition, 2013
th

2 David Beazley, Brian K. Jones, "Python Cookbook", O'Reilly Media, 3 Edition, 2013
rd

3 Mark Lutz, “Python Pocket Reference”, O'Reilly Media, 5 Edition, 2014


th

4 www.python.org
5 www.diveintopython3.net
Unit I
Part A

1. What is meant by interpreter?


An interpreter is a computer program that executes instructions written in a programming
language. It can either execute the source code directly or translate the source code in a
first step into a more efficient representation and executes this code.
2. How will you invoke the python interpreter?
The Python interpreter can be invoked by typing the command "python" without any
parameter followed by the "return" key at the shell prompt.
3. What is meant by interactive mode of the interpreter?
Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory. As new lines are
fed into the interpreter, the fed program is evaluated both in part and in whole.
4. Write a snippet to display “Hello World” in python interpreter.
In script mode:
>>> print "Hello World"
"Hello
World"
'Hello
World'
5. What is a value? What are the different types of values?
A value is one of the fundamental things – like a letter or a number – that a program manipulates.
Its types are: integer, float, boolean, strings and lists.
6. Define a variable and write down the rules for naming a variable.
A name that refers to a value is a variable. Variable names can be arbitrarily long. They can
contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase
letters, but it is good to begin variable names with a lowercase letter.
7. Define keyword and enumerate some of the keywords in Python.
A keyword is a reserved word that is used by the compiler to parse a program. Keywords
cannot be used as variable names. Some of the keywords used in python are: and, del,
from, not, while, is, continue.
8. Define statement and what are its types?
A statement is an instruction that the Python interpreter can execute. There are two types
of statements: print and assignment statement.
9. What do you meant by an assignment statement?
An assignment statement creates new variables and gives them values:
Eg 1: Message = 'And now for something completely different'
Eg 2: n = 17
10. What is tuple?
A tuple is a sequence of immutable Python objects. Tuples are sequences, 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. Creating a tuple is as simple as putting different
comma-separated values. Comma-separated values between parentheses can also be used.
Example: tup1 = ('physics', 'chemistry', 1997,
2000);
11. What is an expression?
An expression is a combination of values, variables, and operators. An expression is
evaluated
using assignment operator.
Examples: Y=x + 17
12. What do you mean by an operand and an operator? Illustrate your answer with relevant
example.
An operator is a symbol that specifies an operation to be performed on the operands. The
data items that an operator acts upon are called operands. The operators +, -, *, / and **
perform addition, subtraction, multiplication, division and exponentiation. Example:
20+32
In this example, 20 and 32 are operands and + is an operator.
13. What is the order in which operations are evaluated? Give the order of precedence.
The set of rules that govern the order in which expressions involving multiple operators and
operands are evaluated is known as rule of precedence. Parentheses have the highest precedence
followed by exponentiation. Multiplication and division have the next highest precedence
followed by addition and subtraction.
14. 14. Illustrate the use of * and + operators in string with example.
The * operator performs repetition on strings and the + operator performs concatenation
on
strings.
Example:
>>> ‘Hello*3’
Output: HelloHelloHello
>>>’Hello+World’
Output: HelloWorld
15. What is the symbol for comment? Give an example.
# is the symbol for comments
in Python. Example:
# compute the percentage of the hour that has elapsed
16. Identify the parts of a function in the given example.
a. betty = type("32")
b. print betty
The name of the function is type, and it displays the type of a value or variable. The value or
variable, which is called the argument of the function, is enclosed in parentheses. The argument
is 32. The function returns the result called return value. The return value is stored in betty.
17. What is a local variable?
A variable defined inside a function. A local variable can only be used inside its function.
18. What is the output of the following?
float(32)
float("3.14159")
Output:
a. 32.0 The float function converts integers to floating-point numbers.
b. 3.14159 The float function converts strings to floating-point numbers.
19. What do you mean by flow of execution?
In order to ensure that a function is defined before its first use, we have to know the order in
which statements are executed, which is called the flow of execution. Execution always begins at
the first statement of the program. Statements are executed one at a time, in order from top to
bottom.
20. Write down the output for the following
program. first = 'throat'
second
=
'warble
r' print
first +
second
Output:
throatwarbler
21. Explain the concept of floor division.
The operation that divides two numbers and chops off the fraction part is known as floor
division.

22. What is type coercion? Give example.


Automatic method to convert between data types is called type coercion. For
mathematical operators, if any one operand is a float, the other is automatically converted
to float.
Eg:
minute = 59
minute / 60.00.983333333333
23. Write a math function to perform √2 / 2.
math.sqrt(2) / 2.0
0.707106781187
24. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and false are
called Boolean values.
Eg :
5 == 5
False
True and False are special values that belongs to the type bool; they are not strings:
25. What are the different types of operators?
o Arithmetic Operator (+, -, *, /, %, **, // )
o Relational operator ( == , !=, <>, < , > , <=, >=)
o Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
o Logical Operator (AND, OR, NOT)
o Membership Operator (in, not in)
o Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary
left shift), >> (binary right shift))
o Identity(is, is not)
26. Explain modulus operator with example.
The modulus operator works on integers and yields the remainder when the first operand is
divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the
same as for other operators:
Eg:
remainder = 7 % 3
print remainder
1
So 7 divided by 3 is 2 with 1 left over.
27. Explain relational operators.
The == operator is one of the relational operators; the others are:
X! = y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

28. Explain Logical operators


There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true only if x
is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean expression,
so not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non-zero number is said
to be true in Boolean expressions.
29. What is conditional execution?
The ability to check the condition and change the behavior of the program accordingly is called
conditional execution. Example:
If statement:
The simplest form of if statement is:
Syntax:
if
statement:
Eg:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.

30. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are two
possibilities and the condition determines which one to execute.
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
31. What are chained conditionals?
Sometimes there are more than two possibilities and we need more than two branches. One way
to express a computation like that is a chained conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'

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

34. What is a break statement?


When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'
35. What is a continue statement?
The continue statement works somewhat like a break statement. Instead of forcing termination, it
forces the next iteration of the loop to take place, skipping any code in between.
Eg:
for num in range(2,10):
if num%2==0;
print “Found an even number”, num
continue
print “Found a number”, num

36. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a
variable on the top of the script or module, the variable is called global variable. The variables
that are defined inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)
37. Compare string and string slices.
A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg: >>> s ='Monty Python'
print s[0:5]
Monty
print s[6:12]
Python

38. Mention a few string functions.


s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in
string

s.lower() – converts a string to lower case


s.split() – returns a list of words in string

39. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
Eg:
def bar():
pass
If the function bar() is called, it does absolutely nothing.

Part B

1. List down the different types of operators with suitable examples.


2. Explain conditional alternative and chained conditional.
3. Explain string slices and string immutability.
4. Explain string functions and methods.
5. Explain in detail about lists, list operations and list slices.
6. Explain in detail about list methods and list loops with examples.
7. Explain in detail about mutability and tuples with a Python program
8. Explain in detail about dictionaries and its operations.
9. Write a Python program for a) selection sort b) insertion sort.
Unit II
Part A

1. What is function call?


A function is a named sequence of statements that performs a computation. When we define a
function, we specify the name and the sequence of statements. Later, we can “call” the function
by its name called as function call.

2. Give the syntax of function definition.


def NAME( LIST OF PARAMETERS ):

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.

6. Write the syntax of lambda function.


Syntax
lambda arguments : expression

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))

9. What are exceptions?


An exception is an error that happens during execution of a program. When that error
occurs, Python generate an exception that can be handled, which avoids your program
to crash.
10. List the common exception error in python.
 ZeroDivisionError
 ValueError
 NameError
 KeyError
 FloatingPointError

11. How exceptions are handled in python?


To use exception handling in Python, you first need to have a catch-all except clause. The words
"try" and "except" are Python keywords and are used to catch exceptions.

try-except [exception-name] (see above for examples) blocks

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?

filename = raw_input('Enter a file name: ')


try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename

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

14. Define regular expression.


Regular expression is a sequence of character(s) mainly used to find and replace patterns in a string
or file. In Python, we have module “re” that helps with regular expressions. So you need to import
library re before you can use regular expressions in Python.

15. What is the use of regular expression?


The most common uses of regular expressions are:

 Search a string (search and match)


 Finding a string (findall)
 Break string into a sub strings (split)
 Replace part of a string (sub)
16. What are the methods provided by re module?
The ‘re’ package provides multiple methods to perform queries on an input string.

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

1. What are modules?


A module is simply a file that defines one or more related functions grouped together. To reuse the
functions of a given module, we need to import the module. Syntax: import <modulename>
2. List the important buit-in modules of python.
 calendar
 cgi
 io
 keyword
 math
 re
 random
3. Write syntax of import statement.
The import Statement
Module contents are made available to the caller with the import statement. The importstatement
takes many different forms, shown below.
import <module_name>
The simplest form is the one already shown above:
import <module_name>

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

Now Child objects behave differently


>>> c = Child()

>>> c.get_value()

10. What is the use of Get and Set Attributes in Python?


Attributes of a class are function objects that define corresponding methods of its instances. They are
used to implement access controls of the classes.
getattr() – This function is used to access the attribute of object.
hasattr() – This function is used to check if an attribute exist or not.
setattr() – This function is used to set an attribute. If the attribute does not exist, then it would be
created.
delattr() – This function is used to delete an attribute. If you are accessing the attribute after deleting
it raises error “class has no attribute”

11. Define Name Mangling.


A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to
avoid naming conflicts in subclasses. This is also called name mangling—the interpreter changes the
name of the variable in a way that makes it harder to create collisions when the class is extended
later.
12. What are Method Types in Python?
1. Decorators
2. Instance methods

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

1. What is a text file?


A text file is a file that contains printable characters and whitespace, organized in to lines separated
by newline characters.

2. Write the syntax of file open function in python.


Before read or write a file, it is necessary to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods
associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
 file_name − The file_name argument is a string value that contains the name of the file that you
want to access.
 access_mode − The access_mode determines the mode in which the file has to be opened, i.e.,
read, write, append, etc. A complete list of possible values is given below in the table. This is
optional parameter and the default file access mode is read (r).

 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).

3. List the different modes of opening a file.

 r - Opens a file for reading only.


 rb - Opens a file for reading only in binary format.
 r+ - Opens a file for both reading and writing.
 rb+ - Opens a file for both reading and writing in binary format.
 w - Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
 wb -Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
 w+ - Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
 wb+ - Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
 a - Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
 Ab - Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
 a+ - Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
 ab+ - Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.

4. Write the syntax of closing a file.


The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();

5. Write a python program that writes “Hello world” into a file.


file.f=open("ex88.txt",'w')
f.write("hello world")
f.close()
6. Write a python program that counts the number of words in a file.
file.f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
7. What are the two arguments taken by the open() function?
The open function takes two arguments : name of the file and the mode of operation.
Example: f = open("test.dat","w")
8. What is a file object?
A file object allows us to use, access and manipulate all the user accessible files. It maintains the
state about the file it has opened.
9.What information is displayed if we print a file object in the given program?
f= open("test.txt","w")
print f
The name of the file, mode and the location of the object will be displayed.
10. How do you delete a file in Python?

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)

11. What is Directory in Python?


A directory or folder is a collection of files and sub directories. Python has the os module, which
provides us with many useful methods to work with directories
12. List the directory operations in python.

 Getting the Current Working Directory - getcwd()


 List Directory Contents - listdir()
 Create a new Directory/Folder - mkdir()
 Creating Subdirectories – makedirs()
 Deleting an empty Directory/Folder - rmdir()
 Renaming a directory/folder - os.rename()

13. What is CSV format?


CSV (Comma Separated Values) is a most common file format that is widely supported by many
platforms and applications. It is easier to export data as a csv dump from one system to another
system. In Python it is simple to read data from csv file and export data to csv. The csv package
comes with very handy methods and arguments to read and write csv file.
Example:
User,Country,Age
Alex,US,25
Ben,US,24
Dennis,UK,25
Yuvi,IN,24

14. What is JSON format?


JSON( Java Script Object Notation) is a lightweight text based data-interchange format which is
completely language independent. It is based on JavaScript. Easy to understand, manipulate and
generate. In Python there are lot of packages to simplify working with json. We are going to use
json module in this tutorial.

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

 Write the JSON to output file

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

1. What is the use of Tkinter?


a. Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
2. List the procedure for creating a GUI application using Tkinter.

a. Import the Tkinter module.


b. Create the GUI application main window.
c. Add one or more of the above-mentioned widgets to the GUI application.
d. Enter the main event loop to take action against each event triggered by the user.

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()

4. List the major widgets of Tkinter?


5. What is the standard attributes of widgets?

Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
6. What are the geometry manager classes of Tkinter ?

The three geometry manager classes of Tkinter .


pack() method:It organizes the widgets in blocks before placing in the parent widget.
grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent
widget.
place() method:It organizes the widgets by placing them on specific positions directed by the
programmer.
7. How events are handled in python?
Tkinter provides a powerful mechanism to deal with events. For each widget, we can bind Python
functions and methods to events.

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.

8. Capturing clicks in a window


from Tkinter import *

root = Tk()

def callback(event):
print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)


frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

9. How sockets are created in python?

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

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]]

11. What are modules/packages supported for sending emails in python?


email
rfc822
smtplib
mimetools
mimetypes
mailbox
12. Define CGI.
The Common Gateway Interface (CGI) is a standard for writing programs that can interact
through a Web server with a client running a Web browser.
CGI is the standard for programs to interface with HTTP servers.
CGI programming is written dynamically generating webpages that respond to user input or
webpages that interact with software on the server
13. What is GET and POST method?
GET requests can include a query string as part of the URL
GET method delivers data as part of URI
When using forms it’s generally better to use POST:
POST method delivers data as the content of a request
<FORM METHOD=POST ACTION=…>
there are limits on the maximum size of a GET query string

a post query string doesn’t show up in the browser as part of the current URL

14. Give example for CGI script.

import cgi def main():


print "Content-type: text/html\n"
form = cgi.FieldStorage() # parse query
if form.has_key("firstname") and form["firstname"].value != "":
print "<h1>Hello", form["firstname"].value, "</h1>"
else:
print "<h1>Error! Please enter first name.</h1>"

15. How to upload file using CGI in python?


import cgi
form = cgi.FieldStorage()
if not form:
print """
<form action="/cgi-bin/test.py" method="POST" enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit">
</form>
"""
elif form.has_key("filename"):
item = form["filename"]
if item.file:
data = item.file.read() # read contents of file
print cgi.escape(data)

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.

You might also like