Monday, May 21, 2012

Some Python Stuff

1. What is Python? State some programming language features of Python.
  • Python is a modern powerful interpreted language with objects, modules, threads, exceptions, and automatic memory managements.
  • Salient features of Python are
-Simple & Easy: Python is simple language & easy to learn.
-Free/open source: it means everybody can use python without purchasing license.
-High level language: when coding in Python one need not worry about low-level details.
-Portable: Python codes are Machine & platform independent.
-Extensible: Python program supports usage of C/ C++ codes.
-Embeddable Language: Python code can be embedded within C/C++ codes & can be used a scripting language.
-Standard Library: Python standard library contains prewritten tools for programming.
-Build-in Data Structure: contains lots of data structure like lists, numbers & dictionarie

2.  Explain how python is interpreted.
Python program runs directly from the source code. Each type Python programs are executed code is required. Python converts source code written by the programmer into intermediate language which is again translated it into the native language / machine language that is executed. So Python is an Interpreted language 
3.  Explain the disadvantages of python.
  • Python isn't the best for memory intensive tasks.
  • Python is interpreted language & is slow compared to C/C++ or java.
  • Python not a great choice for a high-graphic 3d game that takes up a lot of CPU.
  • Python is evolving continuously, with constant evolution there is little substantial documentation available for the language.

 ------------------------------
4. When to use list vs. tuple vs. dictionary vs. set?
List is like array, it can be used to store homogeneous as well as heterogeneous data type (It can store same data type as well as different data type). List are faster compared to array. Individual element of List data can be accessed using indexing & can be manipulated.
List Code Snippet:
list = ["Sarah",29,30000.00]
for i in range (3):
     print list[i]
------------------
Output
Sarah
29
30000.0
Tuples are similar to lists, but there data can be changed once created throught the execution of program. Individual element of Tuples can be accessed using indexing.
Tuples Code Snippet: The Days
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print days
------------------------------
('Sunday', 'Mondays', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
Sets stores unordered values & have no index. And unlike Tuples and Lists, Sets can have no duplicate data, It is similar to Mathematical sets.
  • add() function can be used to add element to a set.
  • update() function can be used to add a group of elements to a set.
  • Copy() function can be used to create clone of set.
Set Code Snippet:
disneyLand = set (['Minnie Mouse', 'Donald Duck', 'Daisy Duck', 'Goofy'])
disneyLand.add('Pluto')
print disneyLand
-----------------------------------------------
Output
set(['Goofy', 'Daisy Duck', 'Donald Duck', 'Minnie Mouse', ’Pluto’])
Dictionary are similar to what their name is. In a dictionary, In python, the word is called a 'key', and the definition a 'value'. Dictionaries consist of pairs of keys and their corresponding values.
Dictionary Code Snippet:
>>> dict = {'India': 'Bharat', 'Angel': ‘Mother Teresa’, 'Cartoon': 'Mickey'}
>>>print dict[India]
Bharat
>>>print dict[Angel]
Mother Teresa

----------------------------------------
5. Describe how exceptions are handled in python.
Errors detected during execution of program are called exceptions. Exceptions can be handled using the try..except statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.
try…except demo code:
>>> while True:
try:
         x = int(raw_input("Enter no. of your choice: "))
         break
except ValueError:
         print "Oops! Not a valid number. Attempt again"
Enter no. of your choice: 12ww
Oops! Not a valid number. Attempt again
Enter no. of your choice: hi there
Oops! Not a valid number. Attempt again
Enter no. of your choice: 22
>>> 

------
6. Describe how to implement Cookies for Web python.
A cookie is an arbitrary string of characters that uniquely identify a session.
Each cookie is specific to one Web site and one user.
The Cookie module defines classes for abstracting the concept of cookies. It contains following method to creates cookie
  • Cookie.SimpleCookie([input])
  • Cookie.SerialCookie([input]
  • Cookie.SmartCookie([input])
for instance following code creates a new cookie ck-
import Cookie
ck= Cookie.SimpleCookie ( x ) 


--------
7. Describe how to use Sessions for Web python.
Sessions are the server side version of cookies. While a cookie preserves state at the client side, sessions preserves state at server side.
The session state is kept in a file or in a database at the server side. Each session is identified by a unique session id (SID). To make it possible to the client to identify himself to the server the SID must be created by the server and sent to the client whenever the client makes a request.
Session handling is done through the web.session module in the following manner:
import web.session session = web.session.start( option1, Option2,... )
session['myVariable'] = 'It can be requested' 

--
8. What is a negative index in python?
  • Python arrays & list items can be accessed with positive or negative numbers (also known as index).
  • For instance our array/list is of size n, then for positive index 0 is the first index, 1 second, last index will be n-1. For negative index, -n is the first index, -(n-1) second, last negative index will be – 1.
  • A negative index accesses elements from the end of the list counting backwards.
  • An example to show negative index in python
>>> import array
>>> a= [1, 2, 3]
>>> print a[-3]
1
>>> print a[-2]
2
>>> print a[-1]
3
-------
9. What are the rules for local and global variables in Python?
If a variable is defined outside function then it is implicitly global. If variable is assigned new value inside the function means it is local. If we want to make it global we need to explicitly define it as global. Variable referenced inside the function are implicit global. Following code snippet will explain further the difference
#!/usr/bin/python
# Filename: variable_localglobal.py
def fun1(a):
            print 'a:', a
            a= 33;
            print 'local a: ', a
a = 100
fun1(a)
print 'a outside fun1:', a
def fun2():
           global b
           print 'b: ', b
           b = 33
           print 'global b:', b
b =100
fun2()
print 'b outside fun2', b
-------------------------------------------------------
Output
$ python variable_localglobal.py
a: 100
local a: 33
a outside fun1: 100
b :100
global b: 33
b outside fun2: 33


10. What are the steps required to make a script executable on Unix?
The steps that are required to make a script executable are to:

• First create a script file and write the code that has to be executed in it.
• Make the file mode as executable by making the first line starts with #! this is the line that python interpreter reads.
• Set the permission for the file by using chmod +x file. The file uses the line that is the most important line to be used:
#!/usr/local/bin/python
• This explains the pathname that is given to the python interpreter and it is independent of the environment programs.
• Absolute pathname should be included so that the interpreter can interpret and execute the code accordingly. The sample code that is written:

#! /bin/sh
# Write your code here
exec python $0 ${1+"$@"}
# Write the function that need to be included.

11. Write a program to read and write the binary data using python?
The module that is used to write and read the binary data is known as struct. This module allows the functionality and with it many functionalities to be used that consists of the string class. This class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is:

import struct
f = open(file-name, "rb")
# This Open() method allows the file to get opened in binary mode to make it portable for # use.
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
The ‘>” is used to show the format string that allows the string to be converted in big-endian data form. For homogenous list of data the array module can be used that will allow the data to be kept more organized fashion.

12. Write a program to show the singleton pattern used in python.
Singleton patter is used to provide a mechanism that limits the number of instances that can be used by one class. It also allows the same object to be shared between many different parts of the code. This allows the global variables to be used as the actual data that is used is hidden by the singleton class interface. The singleton class interface can have only one public member and one class method Handle. Private constructors are not used to create an object that is used outside the class. The process waits for the static member function to create new instances and return the singleton object. The code that is used to call the singleton object is:

Singleton& Singleton::Handle()
{
if( !psingle ) {
psingle = new Singleton;
}
return *psingle;
}
13. What is LIST comprehensions features of Python used for?
  • LIST comprehensions features were introduced in Python version 2.0, it creates a new list based on existing list.
  • It maps a list into another list by applying a function to each of the elements of the existing list.
  • List comprehensions creates lists without using map() , filter() or lambda form.

14. What is Docstring
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docsting is defined by including a string constant as the first statement in the object's definition. For example, the following function defines a docstring: 

def x_intercept(m, b):
    """
    Return the x intercept of the line y=m*x+b.  The x intercept of a
    line is the point at which it crosses the x axis (y=0).
    """
    return -b/m

15. Write a program to print all the contents of a file

Ans.


try:
  f1=open("filename.txt","r")
except Exception, e:
  print "%s" %e 

print f1.readlines()
Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines.
f1=open("filename.txt","r")
leng=f1.readline()
print len(leng) -1, "is the length of the string"

Since the last character is a whitespace we deduct 1 out of the length returned by the len() function.


16.  Remove the whitespaces from the string.
s
 = 'aaa                  bbb                                   ccc     
             ddd                                                       
               eee'

Ans.

a = string.split(s)
print a
['aaa', 'bbb', 'ccc', 'ddd', 'eee'] # This is the output of print a

print string.join(a)
aaa bbb ccc ddd eee  # This is the output of print string.join(a)
17. What do youknow about various Python web frameworks
Knowing a few names is usually good enough, though
knowledge about the frameworks is a nice plus) such as
Django, TurboGears, Zope, etc.

18 What do you know about various Python GUI frameworks and
the pros/cons of them (tkinter, wx, pykde, etc)

19Where do you go with Python related questions (c.l.p,
google, google-groups, etc)
20. General- Tabs vs. spaces, and their reasoning. choice of editor/IDE?




No comments: