(2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to...

28
(2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Makesuitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together. (4) Numbers to the right indicate marks. (5) Draw neat labeled diagrams wherever necessary. (6) Use of Non-programmable calculators is allowed. 1 Attempt any three of the following: 15 a What is Python? List and explain feature of Python. Answer: Easy‐to‐learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy‐to‐read − Python code is more clearly defined and visible to the eyes. Easy‐to‐maintain − Python's source code is fairly easy‐to‐maintain. A broad standard library − Python's bulk of the library is very portable and cross‐ platform compatible on UNIX, Windows, and Macintosh. Interactive Mode − Python has support for an interacƟve mode which allows interactive testing and debugging of snippets of code. Portable − Python can run on a wide variety of hardware plaƞorms and has the same interface on all platforms. Extendable − You can add low‐level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases − Python provides interfaces to all major commercial databases. GUI Programming − Python supports GUI applicaƟons that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable − Python provides a beƩer structure and support for large programs than shell scripting. b Write the steps to install Python and to run Python code. Answer(following steps may vary depending on the version): Steps to install Python: We first need to download Python installer from the link http://www.python.org/downloads/release/python‐342/. Here we can find the 3.4.2 64 bit version of Python under the link “Windows x86‐64 MSI installer” Download it. After downloading the setup file, double click on the installer file, which then will open the installer window.

Transcript of (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to...

Page 1: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

(2½ hours) Total Marks: 75

N. B.: (1) All questions are compulsory. (2) Makesuitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together. (4) Numbers to the right indicate marks. (5) Draw neat labeled diagrams wherever necessary. (6) Use of Non-programmable calculators is allowed. 1 Attempt any three of the following:  15

a What is Python? List and explain feature of Python. Answer: 

Easy‐to‐learn −  Python  has  few  keywords,  simple  structure,  and  a  clearly  defined syntax. This allows the student to pick up the language quickly. 

Easy‐to‐read − Python code is more clearly defined and visible to the eyes. 

Easy‐to‐maintain − Python's source code is fairly easy‐to‐maintain. 

A broad  standard  library −  Python's  bulk  of  the  library  is  very  portable  and  cross‐platform compatible on UNIX, Windows, and Macintosh. 

Interactive  Mode −  Python  has  support  for  an  interac ve  mode  which  allows interactive testing and debugging of snippets of code. 

Portable − Python can run on a wide variety of hardware pla orms and has the same interface on all platforms. 

Extendable −  You  can  add  low‐level  modules  to  the  Python  interpreter.  These modules  enable  programmers  to  add  to  or  customize  their  tools  to  be  more efficient. 

Databases − Python provides interfaces to all major commercial databases. 

GUI  Programming −  Python  supports  GUI  applica ons  that  can  be  created  and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. 

Scalable − Python provides a be er  structure and  support  for  large programs  than shell scripting. 

 

b Write the steps to install Python and to run Python code. Answer(following steps may vary depending on the version):  Steps to install Python:  

We first need to download Python installer from the link 

http://www.python.org/downloads/release/python‐342/. Here we can find the 3.4.2 

64 bit version of Python under the link “Windows x86‐64 MSI installer” Download it. 

 

After downloading the setup file, double click on the installer file, which then will 

open the installer window. 

 

Page 2: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

The first window asks us about for which user we want to allow to use the installed 

Python. 

 

After clicking the next button the installer asks the path information for installation. 

After selecting the appropriate path click next button. 

 

The next screen is to ask to customize the installation. To keep default selection click 

on next. After that installation begins 

 

At the end the last screen asks for finishing the installation. After clicking the finish 

button now we all set to use the Python. 

Running Python code: After successful installation to run the Python program, we have to launch the IDLE(Integrated Development and Learning Environment) to write the Python code. We launch it by going through Programs‐> Python‐> python IDLE.   After opening the IDLE we can type our Python code.   After finishing the code hit the ENTER key to execute the code.  

c Explain type conversion of variable in Python.Answer: Type Conversion (any five types with example) 

Sometimes it's necessary to perform conversions between the built‐in types. To convert between types you simply use the type name as a function. In addition, several built‐in functions are supplied to perform special kinds of conversions. All of these functions return a new object representing the converted value. 

Function  Description

int(x ) example: >>> int(45.67) 45 

Converts x to a plain integer. 

long(x) Example: print(long(67.898)) output: 67 

Converts x to a long integer. 

float(x) Example: >>> float(34) 34.0 

Converts x to a floating‐point number. 

complex(real [,imag]) Example: >>> complex(45,4) 

Creates a complex number. 

Page 3: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

(45+4j)  

str(x) Example: >>> str(2) '2'  

Converts object x to a string representation.

unichr(x) Example: print(unichr(65)) output: A 

Converts an integer to a Unicode character. 

  

d Explain if…else statement with example. Answer: 

Syntax 

The syntax of the if...else statement is –  if test‐expression:    statement(s) else:    statement(s) 

The if..else statement evaluates test‐expression and will execute body of if only when test condition is True. 

If the condition is False, body of else is executed. Indentation is used to separate the blocks. 

Flow Diagram 

  Example: temperature = float(input('What is the temperature? ')) 

Page 4: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

    if temperature > 48:         print('It is too hot.')     else:         print('It is not too hot.')   

e Explain the use of break statement in a loop with example.Answer: 

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. 

If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop. 

Syntax of break 

break 

The working of break statement in for loop and while loop is shown below. 

  

f. What is the difference between interactive mode and script mode in Python? Answer:  Pnython has two basic modes: script and interactive. The normal mode is the mode where the scripted and finished .py files are run in the Python interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.  In interactive mode, Python displays the results of expressions. In script mode, however, Python doesn't automatically display results. Interactive mode allows interactive testing and debugging of snippets of code.  Example‐Interactive mode: A sample interactive session:  >>> 5 

Page 5: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

5 >>> print(5*7) 35 >>> "hello" * 4 'hellohellohellohello'  Script Mode: In a  script mode  code  is written  in a  separate  file and  it  is  saved with an extension  .py. Then it can be executed by selecting ‘Run Module’ option from Run menu.    Example: file name‐example.py a=10 if(a>5):    print("Greater") else:     print("Smaller")  After running above code in script mode: output: Greater   

   

2 Attempt any three of the following:  15

a How function is defined and called in Python?  Answer: 

Syntax of Function 

def function_name(parameters):   """docstring"""   statement(s)  Above shown is a function definition which consists of following components. 

1. Keyword def marks the start of function header. 2. A function name to uniquely identify it. Function naming follows the same rules of 

writing identifiers in Python. 3. Parameters (arguments) through which we pass values to a function. They are 

optional. 4. A colon (:) to mark the end of function header. 5. Optional documentation string (docstring) to describe what the function does. 6. One or more valid python statements that make up the function body. Statements 

must have same indentation level (usually 4 spaces). 7. An optional return statement to return a value from the function. 

Example of a function definition: 

def greet(name): #This function greets to the person passed in as parameter      print("Hello, "+name+". Good morning!")  Function Call Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate 

Page 6: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

parameters.  # Calling a function function_name(parameter_list)  Example: >>> greet('Paul') Hello, Paul. Good morning!   

b Write a  function  that  takes  single  character and prints  ‘character  is  vowel’  if  it  is  vowel, ‘character is not vowel’ otherwise.  Answer:  def vchk(ch):    if(ch=='a'  or  ch=='A'  or  ch=='e'  or  ch=='E'  or  ch=='i'  or  ch=='I'  or  ch=='o'  or  ch=='O'  or ch=='u' or ch=='U'):      print(ch,"character is vowel ")    else:      print( ch, "character is not vowel ")  ch=input("Enter any single character:  ") vchk(ch) Output: Enter any single character:  o  o character is vowel  

c Short note on incremental development. Answer: If the code is bigger, we have to spend the maximum time to debug. To simply this task of dealing with  large code we can use a process called  incremental development. The goal of incremental development  is  to avoid  long debugging sessions by adding and testing only a small amount of code at a time. The key aspects of the process are: 

1. Start with a working program and make small  incremental changes. At any point,  if there is an error, you will know exactly where it is. 

2. Use  temporary  variables  to  hold  intermediate  values  so  you  can  output  and  check them. 

3. Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements  into compound expressions, but only  if  it does not make the program difficult to read. 

Example: Suppose we want to find the area of a circle, given by the radius r.   

The formula is    Step1: At this step we can establish the  input (the parameters) and the output (that  it  the return  value).  In  this  case,  the  radius  is  the  input,  which  we  can  represent  using  one parameter. The return value is the area, which is a floating‐point value.  Step2: Build the code block that calculates the area of a circle. >>>defcarea(r)        Return 0.0 This function doesn’t compute are; it always returns zero. But it is syntactically correct, and we can test it before we make it more complicated.

Page 7: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

>>>crea(2) 0.0  Step3: Next we compute the area of a circle by using formula(3.14*r*r). Here 3.14 is value of . 

>>>defcarea®     a=3.14*r*r      Return a  

d What  is  recursive  function? Write  a  Python  program  to  calculate  factorial  of  a  number using recursive function? Answer: Recursive  function:  it  is  a  function  that  calls  itself.  Every  recursive  function must  have  a base condition that stops the recursion or else the function calls itself infinitely.  # An example of a recursive function to # find the factorial of a number  def calc_factorial(x):     #This is a recursive function to find the factorial of an integer      if x == 1:         return 1     else:         return (x * calc_factorial(x‐1))  num = 4 print("The factorial of", num, "is", calc_factorial(num))  Output: The factorial of 4 is 24  

e Explain various string operations that can be performed using operators in Python. Answer(any five with example):  

Following table shows various operations performed on strings using various operators  

Assume string variable a holds 'Hello' and variable b holds 'Python', then − 

Operator  Description  Example 

+  Concatenation ‐ Adds values on either side of the operator  a + b will give HelloPython

*  Repetition ‐ Creates new strings, concatenating multiple copies of the same string 

a*2 will give ‐HelloHello 

[]  Slice ‐ Gives the character from the given index  a[1] will give e 

Page 8: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

[ : ]  Range Slice ‐ Gives the characters from the given range a[1:4] will give ell 

in  Membership ‐ Returns true if a character exists in the given string 

H in a will give 1 

not in  Membership ‐ Returns true if a character does not exist in the given string 

M not in a will give 1 

r/R  Raw String ‐ Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. 

print r'\n' prints \n and print R'\n'prints \n 

%  Format ‐ Performs String formatting  See at next section 

 

f. Explain str.find() function with suitable example. Answer: str.find() function determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given. 

Syntax 

str.find(str, beg=0, end=len(string)) 

Parameters 

str − This specifies the string to be searched. 

beg − This is the star ng index, by default its 0. 

end − This is the ending index, by default its equal to the length of the string. 

Return Value 

Index if found and ‐1 otherwise. 

Example 

# Example of find method of string 

str1 ="This is University of Mumbai"; 

str2 ="Uni"; 

 

print (str1.find(str2)) 

print (str1.find(str2,10)) 

print (str1.find(str2,40)) 

Page 9: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

 Output: 8 ‐1 ‐1 

   

3 Attempt any three of the following: 15

a What is list? How to create list? 

Answer: 

The  list  is  a most  versatile  datatype  available  in  Python which  can  be written  as  a  list  of comma‐separated values  (items) between square brackets.  Important  thing about a  list  is that items in a list need not be of the same type. Unlike tuple, list is mutable means we can change the values in the list. 

Creating List: 

In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. 

It can have any number of items and they may be of different types (integer, float, string etc.). 

# empty list 

my_list1=[] 

 

# list of integers 

my_list2=[1,2,3] 

 

# list with mixed datatypes 

my_list3=[1,"Hello",3.4] 

 

b Explain try…except blocks for exception handling in Python.Answer: If an error  is encountered, a  try block code execution  is stopped and transferred down to the  except  block.  If  you have  some suspicious code  that may  raise  an  exception,  you  can defend  your  program  by  placing  the  suspicious  code  in  a try: block.  After  the  try:  block, include  an except: statement,  followed  by  a  block  of  code which handles  the problem  as elegantly as possible. 

Syntax 

Here is simple syntax of try....except...else blocks − 

try:    You do your operations here;    ...................... except ExceptionI:    If there is ExceptionI, then execute this block. except ExceptionII: 

Page 10: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

   If there is ExceptionII, then execute this block.    ...................... else:    If there is no exception then execute this block.   Example: while True:        try:               x = int(input("Please enter a number: "))               break        except ValueError:               print ("Oops!  That was no valid number.  Try again...")  Output: Please enter a number: w Oops!  That was no valid number.  Try again... Please enter a number: 8 >>> 

c Explain various built‐in list functions and methods. Answer(any five with example): 

Python List Methods 

append() ‐ Add an element to the end of the list

extend() ‐ Add all elements of a list to the another list 

insert() ‐ Insert an item at the defined index 

remove() ‐ Removes an item from the list

pop() ‐ Removes and returns an element at the given index

clear() ‐ Removes all items from the list 

index() ‐ Returns the index of the first matched item 

count() ‐ Returns the count of number of items passed as an argument 

sort() ‐ Sort items in a list in ascending order

reverse() ‐ Reverse the order of items in the list 

copy() ‐ Returns a shallow copy of the list  

d What is tuple in python? How to create and access it? Answer: 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. 

Creating a  tuple  is as simple as putting different comma‐separated values. Optionally you can put these comma‐separated values between parentheses also. For example − 

Page 11: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; 

The empty tuple is written as two parentheses containing nothing − 

tup1 = (); 

To write a tuple containing a single value you have to include a comma, even though there is only one value − 

tup1 = (50,); 

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on. 

Accessing Values in Tuples 

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example − 

#!/usr/bin/python 

 

tup1 =('physics','chemistry',1997,2000); 

tup2 =(1,2,3,4,5,6,7); 

print"tup1[0]: ", tup1[0] 

print"tup2[1:5]: ", tup2[1:5] 

When the above code is executed, it produces the following result − 

tup1[0]:  physics tup2[1:5]:  [2, 3, 4, 5] 

 

e Explain the properties of dictionary keys.Answer: 

Properties of Dictionary Keys 

Dictionary  values  have  no  restrictions.  They  can  be  any  arbitrary  Python  object,  either standard objects or user‐defined objects. However, same is not true for the keys. 

There are two important points to remember about dictionary keys − 

(a) More  than  one  entry  per  key  not  allowed. Which means  no  duplicate  key  is  allowed. When  duplicate  keys  encountered  during  assignment,  the  last  assignment  wins.  For example − 

#!/usr/bin/python 

 

dict={'Name':'Zara','Age':7,'Name':'Manni'} 

print"dict['Name']: ",dict['Name'] 

When the above code is executed, it produces the following result − 

Page 12: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

dict['Name']:  Manni 

 

(b) Keys  must  be  immutable.  Which  means  you  can  use  strings,  numbers  or  tuples  as dictionary keys but something like ['key'] is not allowed. Following is a simple example − 

#!/usr/bin/python 

 

dict={['Name']:'Zara','Age':7} 

print"dict['Name']: ",dict['Name'] 

When the above code is executed, it produces the following result − 

Traceback (most recent call last):    File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable 

 

f. Explain open() and close() methods for opening and closing a file.Answer: 

How to open a file? 

Python has a built‐in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. 

>>> f = open("test.txt")# open file in current directory 

>>> f = open("C:/Python33/README.txt")# specifying full path 

We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode. 

The default is reading in text mode. In this mode, we get strings when reading from the file. 

On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non‐text files like image or exe files. 

Python File Modes 

Mode  Description 

'r'  Open a file for reading. (default)

'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 

Page 13: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

'x'  Open a file for exclusive creation. If the file already exists, the operation fails. 

'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 

't'  Open in text mode. (default) 

'b'  Open in binary mode. 

'+'  Open a file for updating (reading and writing)

f = open("test.txt")# equivalent to 'r' or 'rt' 

f = open("test.txt",'w')# write in text mode 

f = open("img.bmp",'r+b')# read and write in binary mode 

Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings). 

Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf‐8' in Linux. 

So, we must not also rely on the default encoding or else our code will behave differently in different platforms. 

Hence, when working with files in text mode, it is highly recommended to specify the encoding type. 

f = open("test.txt",mode='r',encoding='utf‐8') 

How to close a file Using Python? 

When we are done with operations to the file, we need to properly close the file. 

Closing a file will free up the resources that were tied with the file and is done using Python close() method. 

Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close the file. 

f = open("test.txt",encoding='utf‐8') 

# perform file operations 

f.close() 

 

   

4 Attempt any three of the following:  15

Page 14: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

a What is regular expression? Explain various patterns of regular expression. Answer(RE + any five patterns with example): Regular expression:  A regular expression is a special sequence of characters that helps you match or  find other strings or sets of strings, using a specialized syntax held in a pattern.  

Regular Expression Patterns 

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash. 

Following table lists the regular expression syntax that is available in Python − 

Sr.No.  Pattern & Description 

1  ^ 

Matches beginning of line. 

2  $ 

Matches end of line. 

3  . 

Matches  any  single  character  except  newline.  Using  m  option  allows  it  to match newline as well. 

4  [...] 

Matches any single character in brackets. 

5  [^...] 

Matches any single character not in brackets 

6  re* 

Matches 0 or more occurrences of preceding expression. 

7  re+ 

Matches 1 or more occurrence of preceding expression. 

8  re? 

Matches 0 or 1 occurrence of preceding expression. 

9  re{ n} 

Matches exactly n number of occurrences of preceding expression. 

10  re{ n,} 

Page 15: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

Matches n or more occurrences of preceding expression.

11  re{ n, m} 

Matches at least n and at most m occurrences of preceding expression. 

12  a| b 

Matches either a or b. 

13  (re) 

Groups regular expressions and remembers matched text. 

14  (?imx) 

Temporarily  toggles  on  i,  m,  or  x  options  within  a  regular  expression.  If  in parentheses, only that area is affected. 

15  (?‐imx) 

Temporarily  toggles  off  i,  m,  or  x  options  within  a  regular  expression.  If  in parentheses, only that area is affected. 

16  (?: re) 

Groups regular expressions without remembering matched text. 

17  (?imx: re) 

Temporarily toggles on i, m, or x options within parentheses. 

18  (?‐imx: re) 

Temporarily toggles off i, m, or x options within parentheses. 

19  (?#...) 

Comment. 

20  (?= re) 

Specifies position using a pattern. Doesn't have a range. 

21  (?! re) 

Specifies position using pattern negation. Doesn't have a range. 

22  (?> re) 

Matches independent pattern without backtracking. 

23  \w 

Page 16: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

Matches word characters.

24  \W 

Matches nonword characters. 

25  \s 

Matches whitespace. Equivalent to [\t\n\r\f]. 

26  \S 

Matches nonwhitespace. 

27  \d 

Matches digits. Equivalent to [0‐9]. 

28  \D 

Matches nondigits. 

29  \A 

Matches beginning of string. 

30  \Z 

Matches end of string. If a newline exists, it matches just before newline. 

31  \z 

Matches end of string. 

32  \G 

Matches point where last match finished. 

33  \b 

Matches word boundaries when outside brackets. Matches backspace  (0x08) when inside brackets. 

34  \B 

Matches nonword boundaries. 

35  \n, \t, etc. 

Matches newlines, carriage returns, tabs, etc. 

36  \1...\9 

Matches nth grouped subexpression. 

 

Page 17: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

b Explain match() function with suitable example. Answer: 

The match Function 

This function attempts to match RE pattern to string with optional flags. 

Here is the syntax for this function − 

re.match(pattern, string, flags=0) 

Here is the description of the parameters − 

Sr.No.  Parameter & Description 

1  pattern 

This is the regular expression to be matched. 

2  string 

This  is  the  string,  which  would  be  searched  to  match  the  pattern  at  the beginning of string. 

3  flags 

You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. 

The re.match function  returns  a match object  on  success, None on  failure.  We usegroup(num) or groups() function of match object to get matched expression. 

Sr.No.  Match Object Method & Description 

1  group(num=0) 

This method returns entire match (or specific subgroup num) 

2  groups() 

This method returns all matching subgroups in a tuple (empty if there weren't any) 

Example 

#!/usr/bin/python 

import re 

 

line ="Cats are smarter than dogs" 

matchObj=re.match( r'(.*) are (.*?) .*', line,re.M|re.I) 

ifmatchObj: 

Page 18: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

print"matchObj.group() : ",matchObj.group() 

print"matchObj.group(1) : ",matchObj.group(1) 

print"matchObj.group(2) : ",matchObj.group(2) 

else: 

print"No match!!" 

When the above code is executed, it produces following result − 

matchObj.group() :  Cats are smarter than dogs matchObj.group(1) :  Cats matchObj.group(2) :  smarter 

 

c What is method overriding? Write an example. Answer: 

Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other. If there is any method in the superclass and a method with the same name in a subclass, then by executing the method, the method of the corresponding class will be executed. Make it clearer with an example 

 

class Rectangle(): 

  def __init__(self,length,breadth): 

    self.length = length 

    self.breadth = breadth 

  defgetArea(self): 

    print self.length*self.breadth," is area of rectangle" 

class Square(Rectangle): 

  def __init__(self,side): 

    self.side = side 

    Rectangle.__init__(self,side,side) 

  defgetArea(self): 

    print self.side*self.side," is area of square" 

s = Square(4) 

r = Rectangle(2,4) 

s.getArea() 

r.getArea() 

 

Output: 

16 is area of square  

Page 19: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

8 is area of rectangle 

Since the method from the coressponding class came into action, it means that one overrode the other. Execution of 'getArea' on the object of Rectangle (r) printed "8 is area of rectangle" from the 'getArea' defined in the Rectangle class whereas, execution of 'getArea' on the object of Square (s) printed "16 is area of square" from the 'getArea' defined in the Square class. It is very useful because it prevents us from making methods with different names and remembering them all. 

 

d What is multithreaded programming? Explain _thread module with suitable example. Answer: Multithreading: Multithreading is  defined as  the ability of  a processor  to execute multiple threads concurrently.  Consider the diagram below in which a process contains two active threads: 

 

Multithreading in Python  

Thread module: Syntax: thread.start_new_thread ( function, args[, kwargs] )  The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.  Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.  Example #!/usr/bin/python  import thread import time  # Define a function for the thread defprint_time( threadName, delay):    count = 0    while count < 5: time.sleep(delay)       count += 1       print "%s: %s" % ( threadName, time.ctime(time.time()) )  # Create two threads as follows 

Page 20: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

try: thread.start_new_thread( print_time, ("Thread‐1", 2, ) ) thread.start_new_thread( print_time, ("Thread‐2", 4, ) ) except:    print "Error: unable to start thread"  while 1:    pass   When the above code is executed, it produces the following result −  Thread‐1: Thu Jan 22 15:42:17 2009 Thread‐1: Thu Jan 22 15:42:19 2009 Thread‐2: Thu Jan 22 15:42:19 2009 Thread‐1: Thu Jan 22 15:42:21 2009 Thread‐2: Thu Jan 22 15:42:23 2009 Thread‐1: Thu Jan 22 15:42:23 2009 Thread‐1: Thu Jan 22 15:42:25 2009 Thread‐2: Thu Jan 22 15:42:27 2009 Thread‐2: Thu Jan 22 15:42:31 2009 Thread‐2: Thu Jan 22 15:42:35 2009 Although it is very effective for low‐level threading, but the thread module is very limited compared to the newer threading module.  

e What is module? What are the advantages of using module? Answer: Module: 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. 

Advantages: Python provides the following advantages for using module: 1) Reusability: Module can be used in some other python code. Hence it provides the facility of code reusability. 

2) Categorization: Similar type of attributes can be placed in one module. 

3) Python modules are easy to write and to import 

 

f. Explain various methods of math module. Answer: (Any five functions with example are expected) 

Function  Description 

ceil(x)  Returns the smallest integer greater than or equal to x. 

copysign(x, y)  Returns x with the sign of y 

Page 21: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

fabs(x)  Returns the absolute value of x 

factorial(x)  Returns the factorial of x 

floor(x)  Returns the largest integer less than or equal to x

fmod(x, y)  Returns the remainder when x is divided by y

frexp(x)  Returns the mantissa and exponent of x as the pair (m, e) 

fsum(iterable)  Returns an accurate floating point sum of values in the iterable 

isfinite(x)  Returns True if x is neither an infinity nor a NaN (Not a Number) 

isinf(x)  Returns True if x is a positive or negative infinity

isnan(x)  Returns True if x is a NaN 

ldexp(x, i)  Returns x * (2**i) 

modf(x)  Returns the fractional and integer parts of x

trunc(x)  Returns the truncated integer value of x

exp(x)  Returns e**x 

expm1(x)  Returns e**x ‐ 1 

log(x[, base])  Returns the logarithm of x to the base (defaults to e) 

log1p(x)  Returns the natural logarithm of 1+x

log2(x)  Returns the base‐2 logarithm of x 

log10(x)  Returns the base‐10 logarithm of x 

pow(x, y)  Returns x raised to the power y 

sqrt(x)  Returns the square root of x

acos(x)  Returns the arc cosine of x 

asin(x)  Returns the arc sine of x 

atan(x)  Returns the arc tangent of x 

atan2(y, x)  Returns atan(y / x)

cos(x)  Returns the cosine of x

hypot(x, y)  Returns the Euclidean norm, sqrt(x*x + y*y) 

Page 22: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

sin(x)  Returns the sine of x 

tan(x)  Returns the tangent of x 

degrees(x)  Converts angle x from radians to degrees

radians(x)  Converts angle x from degrees to radians

acosh(x)  Returns the inverse hyperbolic cosine of x 

asinh(x)  Returns the inverse hyperbolic sine of x 

atanh(x)  Returns the inverse hyperbolic tangent of x

cosh(x)  Returns the hyperbolic cosine of x

sinh(x)  Returns the hyperbolic cosine of x 

tanh(x)  Returns the hyperbolic tangent of x 

erf(x)  Returns the error function at x

erfc(x)  Returns the complementary error function at x

gamma(x)  Returns the Gamma function at x 

lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x 

pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...) 

e  mathematical constant e (2.71828...) 

   

5 Attempt any three of the following: 15

a Explain Checkbutton widget with example.Answer: The Checkbutton widget is a standard Tkinter widgets used to implement on‐off selections. Checkbuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter calls that function or method. Syntax Here is the simple syntax to create this widget −  w = Checkbutton ( master, option, ... ) Parameters: master − This represents the parent window.  options − Here is the list of most commonly used op ons for this widget. These op ons can be used as key‐value pairs separated by commas.  Example: 

Page 23: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

from Tkinter import * import tkMessageBox import Tkinter  top = Tkinter.Tk() CheckVar1 = IntVar() CheckVar2 = IntVar() C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5,width = 20) C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5,width = 20) C1.pack() C2.pack() top.mainloop() When the above code is executed, it produces the following result − 

  

b Write short note tkMessageBox module. Answer: The  tkMessageBox  module  is  used  to  display  message  boxes  in  your  applications.  This module provides a number of functions that you can use to display an appropriate message. 

Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, and askretryignore. 

Syntax 

Here is the simple syntax to create this widget − 

tkMessageBox.FunctionName(title, message [, options] Parameters FunctionName − This is the name of the appropriate message box function.  title − This is the text to be displayed in the title bar of a message box.  message − This is the text to be displayed as a message.  options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed.  You could use one of the following functions with dialogue box −  showinfo() showwarning() showerror () 

Page 24: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

askquestion() askokcancel() askyesno () askretrycancel ()   Example: Try the following example yourself −  import Tkinter import tkMessageBox  top = Tkinter.Tk() def hello(): tkMessageBox.showinfo("Say Hello", "Hello World")  B1 = Tkinter.Button(top, text = "Say Hello", command = hello) B1.pack()  top.mainloop()  When the above code is executed, it produces the following result − 

  

c What is layout management? Explain pack manager. Answer: Layout management  is  the act of arranging  the widgets  in  the window at proper place  for better display and easy to access for the user.When we design the GUI of our application, we decide what widgets we will use and how we will organise those widgets in the application. To organise our widgets, we use specialised non‐visiblse objects called layout managers. The Tkinter  provides  three  layout  managers  as  pack,  grid  and  place  which  are  known  as Geometry managers.  Pack manager: The Pack geometry manager packs widgets in rows or columns. You can use options like fill, expand, and side to control this geometry manager.  Syntax: widget.pack( pack_options )  where, expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.  

Page 25: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically).  side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.    Example 1:      redbutton = Button(frame, text="Red", fg="red")      redbutton.pack( side = LEFT)     Example 2 with output: from Tkinter import *  root = Tk()  listbox = Listbox(root) listbox.pack(fill=BOTH, expand=1)  for i in range(20):     listbox.insert(END, str(i))  mainloop() 

 The fill option tells the manager that the widget wants fill the entire space assigned to it. The value controls how to fill the space; BOTH means that the widget should expand both horisontally and vertically, X means that it should expand only horisontally, and Y means that it should expand only vertically. 

The expand option tells the manager to assign additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the expand option set to a non‐zero value 

 

d Explain place geometry manager with example. Answer: 

Page 26: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

The place geometry manager organizes widgets by placing them in a specific position in the parent widget. It is usually not a good idea to use place for ordinary window and dialog layouts; its simply too much work to get things working as they should. Use the pack or grid managers for such purposes. 

However, place has its uses in more specialized cases. Most importantly, it can be used by compound widget containers to implement various custom geometry managers. Another use is to position control buttons in dialogs. 

Syntax:    widget.place( place_options ) Here is the list of possible options −  anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)  bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.  height, width − Height and width in pixels.  relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.  relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.  x, y − Horizontal and vertical offset in pixels.  Example Try the following example by moving cursor on different buttons −  from Tkinter import * import tkMessageBox import Tkinter  top = Tkinter.Tk()  def helloCallBack():    tkMessageBox.showinfo( "Hello Python", "Hello World")  B = Tkinter.Button(top, text ="Hello", command = helloCallBack)  B.pack() B.place(bordermode=OUTSIDE, height=100, width=100) top.mainloop() When the above code is executed, it produces the following result − 

Page 27: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

  

e Write and explain the steps insert a row into MySql database with example. Answer:   To insert new rows into a MySQL table, you follow the steps below: 

1. Connect to the MySQL database server by creating a new MySQLConnection object. import mysql.connector  con = mysql.connector.connect(user='root',password='',host='localhost',database='python')  The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object.  2. Open the connection con.open()  3. Initiate a MySQLCursor object from the MySQLConnection object. cur = con.cursor()  4. Execute the INSERT statement to insert data into the intended table. cur.execute("""INSERT INTO table1VALUES (%s,%s)""",("John","Hello"))  5. Close the cursor and database connection. cur.close() con.close()  

f. Write short note on cursor object in Python.  Answer: These objects represent a database cursor, which is used to manage the context of a fetch operation. Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors.  Cursors are created by the connection.cursor() method: they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection.  Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors. Cursors created from different connections can or can not be isolated, depending on the connections’ isolation level. See also rollback() and commit() methods.  Methods: .Open(): Opens the cursor 

Page 28: (2½ hours) All - muresults.netmuresults.net/itacademic/SYBScIT/Sem3/AK/PPS.pdf · We first need to download Python installer from ... f.What is the difference between interactive

.close(): Closes the cursor. 

.execute(): Executes the query against the database. Table. 

.fetchone(): This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available.   Example of using cursor: Initiate a MySQLCursor object from the MySQLConnection (here con) object.     cur = con.cursor() Execute SQL statement cur.execute("SELECT * FROM EMPLOYEE") Close the cursor. cur.close()  Example: # Displaying cursor result using a while loop cursor.execute("SELECT * FROM employees") row = cursor.fetchone() while row is not None:   print(row)   row = cursor.fetchone()  # Using the cursor as iterator cursor.execute("SELECT * FROM employees") for row in cursor:   print(row)