Monday, December 13, 2010

Python S-01

  Command history:

    Alt-p retrieves previous command matching what you have typed.
    Alt-n retrieves next.

beginning-of-line <key-home>
center-insert - <Control-key-l>

>>> import sys
>>> sys.path.append('N:\Personal\wdi_python_code')
>>> from clrscr import clrscr
>>> clrscr()


Ctrl + ArrorDown  ==> to the place you add new command in the command window

Reading the value of global variables is not a problem in general, but one thing may make it problematic. If a local variable or parameter exists with the same name as the global variable you want to access, you can't do it directly. The global variable is shadowed by the local one.
If needed, you can still gain access to the global variable by using the function globals, a close relative of vars, which returns a dictionary with the global variables. (locals returns a dictionary with the local variables.)
For example, if you had a global variable called parameter in the previous example, you couldn't access it from within combine because you have a parameter with the same name. In a pinch, however, you could have referred to it as globals()['parameter']:
>>> def combine(parameter):
        print parameter + globals()['parameter']
...
>>> parameter = 'berry'
>>> combine('Shrub')
Shrubberry


# What is List Comprehensions feature of Python used for?

List comprehensions help to create and manage lists in a simpler and clearer way than using map() filter() and lambda. Each list comprehension consists of an expression followed by a for clause then zero or more for or
if clauses.


# What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?
pass is a no-operation/action statement in python
# If we want to load a module and if it doesn't exist let us not bother let us try to do other task. The following example demonstrates that.
try:
import module1
except:
pass


# What is the built-in function used in Python to iterate over a sequence of numbers?
wdi: there is Iterator Types:
container.__iter_()  -> return an iterator object which can support the floowing methods:
iterator.__iter_()
iterator.next ()

range is the built-in function to be used for interating the sequence of numbers.
for iter in range (0 10):
print iter # prints 0 to 9

for iter in range (0 10 2): # The last argument is the sequence to use. Default is 1.
print iter # prints 0 2 4 6 8


# How is the Implementation of Python's dictionaries done?
A hash value of the key is computed using a hash function The hash value addresses a location in an array of "buckets" or "collision lists" which contains the (key value) pairs. The collision list addressed by the hash
value is searched sequentially until a pair is found with pair[0] == key. There turn value of the lookup is then pair[1].


# Does python support switch or case statement in Python?If not what is the reason for the same?
No. You can use multiple if-else. as there is no need for this.

#
What is the method does join() in python belong to?

This has always confused me. It seems like this would be nicer:

my_list = ["Hello", "world"]
print my_list.join("-")
# Produce: "Hello-world"

Than this:

my_list = ["Hello", "world"]
print "-".join(my_list)
# Produce: "Hello-world"

Is there a specific reason it does it like this?

It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings

Because the join() method is in the string class, instead of the list class?

I agree it looks funny.

See http://www.faqs.org/docs/diveintopython/odbchelper_join.html:

Historical note. When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Lots of people feel the same way, and there's a story behind the join method. Prior to Python 1.6, strings didn't have all these useful methods. There was a separate string module which contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn't move at all but simply stay a part of the old string module (which still has lots of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.

# What is the Java implementation of Python popularly known as?
Jython

# Why isn't all memory freed when Python exits?
Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is however aggressive about cleaning up memory on exit and does try to destroy every single object.

If you want to force Python to delete certain things on deallocation you can use the atexit module to register one or more exit functions to handle those deletions.

# Does Python support strongly for regular expressions? What are the other languages that support strongly for regular expressions?
Yes python strongly support regular expression. Other languages supporting regular expressions are: Delphi Java Java script .NET Perl Php Posix python Ruby Tcl Visual Basic XML schema VB script Visual Basic 6.

#
Which of the languages does Python resemble in its class syntax?
C++ is the appropriate language that Python resemble in its class syntax.

# How is memory managed in Python?
Memory is managed through private heaps. Private heap is managed by python memory manager.

#
Why can't lambda forms in Python contain statements?
A lambda statement is used to create new function objects and then return them at runtime thats why lambda forms in Python didn't contain statement.


>> Possible Interview Topics
 Why Python
signal handlers
threads
Sessions
OOP Concepts

>>
comp.lang.python group recently had a discussion on which interview questions to ask a candidate, with Tim Chase suggesting the following list (redacted from original to include just Python-related material). As you can see, some generic programming questions and some process questions made the list:
  1. Do they know a tuple/list/dict when they see it?
  2. When to use list vs. tuple vs. dictionary vs. set?
  3. Can they use list comprehensions (and know when not to abuse them?)
  4. Can they use tuple unpacking for assignment?
  5. String building. Do they use "+=" or do they build a list and use .join() to recombine them efficiently?
  6. Truth-value testing questions and observations (do they write "if x == True" or do they just write "if x")?
  7. Basic file-processing (iterating over a file's lines)
  8. Basic understanding of exception handling
  9. Questions about the standard library ("do you know if there's a standard library for doing X?", or "in which library would you find [common functionality Y]?") Most of these are related to the more common libraries such as os/os.path/sys/re/itertools
  10. Questions about iterators/generators
  11. Questions about map/reduce/sum/etc family of functions
  12. Questions about "special" methods (__foo__)
  13. Can they manipulate functions as first-class objects (Python makes it easy, but do they know how)
  14. More detailed questions about the std. libraries (such as datetime/email/csv/zipfile/networking/optparse/unittest)
  15. Questions about testing (unittests/doctests)
  16. Questions about docstrings vs. comments, and the "Why" of them
  17. More detailed questions about regular expressions
  18. Questions about mutability
  19. Keyword/list parameters and unpacked keyword arguments
  20. Questions about popular 3rd-party toolkits (BeautifulSoup, pyparsing…mostly if they know about them and when to use them, not so much about implementation details)
  21. Questions about monkey-patching
  22. Questions about PDB
  23. Questions about properties vs. getters/setters
  24. Questions about classmethods
  25. Questions about scope/name-resolution
  26. Use of lambda
  27. Decorators added in which version?
  28. SQL-capable DB in which version?
  29. The difference between "class Foo" and "class Foo(object)"
  30. Questions from "import this" about pythonic code
  31. What do they know 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.
  32. What do they know about various Python GUI frameworks and the pros/cons of them (tkinter, wx, pykde, etc)
  33. Where do they go with Python related questions (c.l.p, google, google-groups, etc)

>> Python Interview Questions

1) Explain about the programming language python?
Python is a very easy language and can be learnt very easily than other programming languages. It is a dynamic object oriented language which can be easily used for software development. It supports many other programming languages and has extensive library support for many other languages.

2) Explain about the use of python for web programming?
Python can be very well used for web programming and it also has some special features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, Webservers, Content Management systems, Web services, Webclient programming, Webservices, etc. Many high end applications can be created with Python because of the flexibility it offers.

3) State some programming language features of Python?
Python supports many features and is used for cutting edge technology.
Some of them are
1) A huge pool of data types such as lists, numbers and dictionaries.
2) Supports notable features such as classes and multiple inheritance.
3) Code can be split into modules and packages which assists in flexibility.
4) It has good support for raising and catching which assists in error handling.
5) Incompatible mixing of functions, strings, and numbers triggers an error which also helps in good programming practices.
6) It has some advanced features such as generators and list comprehensions.
7) This programming language has automatic memory management system which helps in greater memory management.
4) How is python interpreted?
Python has an internal software mechanism which makes your programming easy. Program can run directly from the source code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.

5) Does python support object oriented scripting?
Python supports object oriented programming as well as procedure oriented programming. It has features which make you to use the program code for many functions other than Python. It has useful objects when it comes to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.

6) Describe about the libraries of Python?
Python library is very huge and has some extensive libraries. These libraries help you do various things involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as Twisted, wx python, python imaging library, etc.

7) State and explain about Strings?
Strings are almost used everywhere in python. When you use single and double quotes for a statement in python it preserves the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have created a string in Python you can never change it again.

8) Explain about classes in strings?
Classes are the main feature of any object oriented programming. When you use a class it creates a new type. Creating class is the same as in other programming languages but the syntax differs. Here we create an object or instance of the class followed by parenthesis.

9) What is tuple?
Tuples are similar to lists. They cannot be modified once they are declared. They are similar to strings. When items are defined in parenthesis separated by commas then they are called as Tuples. Tuples are used in situations where the user cannot change the context or application; it puts a restriction on the user.

10) Explain and statement about list?
As the name specifies list holds a list of data items in an orderly manner. Sequence of data items can be present in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be altered at any time.

11) Explain about the dictionary function in Python?
A dictionary is a place where you will find and store information on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that strings should be passed as keys in python. Notice that keys are to be separated by a colon and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.

12) Explain about indexing and slicing operation in sequences?
Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.

13) Explain about raising error exceptions
In python programmer can raise exceptions using the raise statement. When you are using exception statement you should also specify about error and exception object. This error should be related to the derived class of the Error. We can use this to specify about the length of the user name, password field, etc.

14) What is a Lambda form?
This lambda statement is used to create a new function which can be later used during the run time. Make_repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in order to return them during the run time.

15) Explain about assert statement?
Assert statement is used to assert whether something is true or false. This statement is very useful when you want to check the items in the list for true or false function. This statement should be predefined because it interacts with the user and raises an error if something goes wrong.

16) Explain about repr function?
This function is used to obtain a string representation of an object. This function helps you in obtaining a printable representation of the object. This function also makes it possible to obtain specific return from the object. This can be made possible by specifying the repr method in the class.

17) Explain about pickling and unpickling?
Python has a standard module known as Pickle which enables you to store a specific object at some destination and then you can call the object back at later stage. While you are retrieving the object this process is known as unpickling. By specifying the dump function you can store the data into a specific file and this is known as pickling.


>> Python Interview Questions and Answers
http://techpreparation.com/python-interview-questions-answers1.htm

What is Python?
Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

Why can't I use an assignment in an expression?
Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
...do something with line...
}

where in Python you're forced to write this:

while True:
line = f.readline()
if not line:
break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.
There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution:
line = f.readline()
while line:
...do something with line...
line = f.readline()

The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop.
The best approach is to use iterators, making it possible to loop through objects using the for statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply:
for line in f:
... do something with line...

Is there a tool to help find bugs or perform static analysis?
Yes.
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style.

Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.

How do you set a global variable in a function?
Did you do something like this?
x = 1 # make a global
def f():
print x # try to print the global
...
for j in range(100):
if q>3:
x=4

Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the print x attempts to print an uninitialized local variable and will trigger a NameError.
The solution is to insert an explicit global declaration at the start of the function:
def f():
global x
print x # try to print the global
...
for j in range(100):
if q>3:
x=4

In this case, all references to x are interpreted as references to the x from the module namespace.

What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.
Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

How do I share global variables across modules?
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1

main.py:
import config
import mod
print config.x

Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.


# locale module for some internationalization functionality

# For many application, logging( using logging module) will be more appropriate than using print.

# IMPORT

import somemodule

from  somemodule import somemodule

fro somemodule import somefunction, another function, yetanother function

from somemodule import *

import math as math1

from module1 import open as open1

Note: some modules, such as os.path, are arranged hierarchically (inside each other)

No comments:

Post a Comment