CoolInterview.com - World's Largest Collection of Interview Questions & Answers, FAQs, queries, sample papers, exam papers, dumps, what, why, how, where, when questions
Our Services
Get 9,000 Interview Questions & Answers in an eBook.




Get it now !!
Send your Resume to 6000 Companies
Python Interview Questions & Answers - Learning Mode
COOLINTERVIEW.COM WEB INTERVIEW QUESTIONS PYTHON INTERVIEW QUESTIONS QUESTIONS & ANSWERS - LEARNING MODE

Python Interview Questions & Answers - Learning Mode

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. Developer‎: ‎Python Software Foundation. Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability. Python is said to be relatively easy to learn and portable, meaning its statements can be interpreted in a number of operating system.

Try Python Interview Questions & Answers - Exam Mode

1 2 3 4 5 Next

Sort By : Latest First | Oldest First | By Rating

Python Interview Questions & Answers - Learning Mode
Try Python Interview Questions & Answers - Exam Mode
Question: How do I modify a string in place?

Answer: You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:

>>> s = "Hello, world"
>>> a = list(s)
>>>print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>>''.join(a)
'Hello, there!'
CoolInterview.com
Question: How do you make a higher order function in Python?

Answer: You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b):
def result(x):
return a*x + b
return result

Or using a callable object:

class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b

In both cases:

taxes = line Source: CoolInterview.com
Question: How do I avoid blocking in the connect() method of a socket?

Answer: The select module is commonly used to help with asynchronous I/O on sockets. Source: CoolInterview.com
Question: How can I overload constructors (or methods) in Python?

Answer: This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you'd write

class C {
C() { cout << "No arguments "; }
C(int i) { cout << "Argument is " << i << " "; }
}

in Python you have to write a single constructor that catches all cases using default arguments. For example:

class C:
def __init__(self, i=None):
if i is None:
print "No arguments"
else:
pr Source: CoolInterview.com
Question: Where is the math.py (socket.py, regex.py, etc.) source file?

Answer: There are (at least) three kinds of modules in Python:

1. modules written in Python (.py);
2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3. modules written in C and linked with the interpreter; to get a list of these, type:
import sys
print sys.builtin_module_names Source: CoolInterview.com
Question: How do I submit bug reports and patches for Python?

Answer: To report a bug or submit a patch, please use the Roundup installation at http://bugs.python.org/.

You must have a Roundup account to report bugs; this makes it possible for us to contact you if we have follow-up questions. It will also enable Roundup to send you updates as we act on your bug. If you had previously used SourceForge to report bugs to Python, you can obtain your Roundup password through Roundup's password reset procedure. Source: CoolInterview.com
Question: Explain about raising error exceptions

Answer: 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. Source: CoolInterview.com
Question: When I edit an imported module and reimport it, the changes don't show up. Why does this happen?

Answer: For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn't, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:

import modname
reload(modname)

Warning: this technique is not 100% fool-proof. In particular, modules containing statements like

from modnam Source: CoolInterview.com
Question: What's a negative index?

Answer: Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string. Source: CoolInterview.com
Question: How stable is Python?

Answer: Very stable. New, stable releases have been coming out roughly every 6 to 18 months since 1991, and this seems likely to continue. Currently there are usually around 18 months between major releases.

With the introduction of retrospective "bugfix" releases the stability of existing releases is being improved. Bugfix releases, indicated by a third component of the version number (e.g. 2.1.3, 2.2.2), are managed for stability; only fixes for known problems are included in a bugfix release, Source: CoolInterview.com
Question: How do I convert a number to a string?

Answer: To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details. Source: CoolInterview.com
Question: How do I access a module written in Python from C?

Answer: You can get a pointer to the module object as follows:

module = PyImport_ImportModule("<modulename>");

If the module hasn't been imported yet (i.e. it is not yet present in sys.modules), this initializes the module; otherwise it simply returns the value of sys.modules["<modulename>"]. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialized and is stored in sys.modules.

You can then access the module's attrib Source: CoolInterview.com
Question: What is Python good for?

Answer: Python is a high-level general-purpose programming language that can be applied to many different classes of problems.

The language comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystem Source: CoolInterview.com
Question: Explain about repr function?

Answer: 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. Source: CoolInterview.com
Question: How do I generate random numbers in Python?

Answer: The standard module random implements a random number generator. Usage is simple:

import random
random.random()

This returns a random floating point number in the range [0, 1). Source: CoolInterview.com
Question: How do I tell "incomplete input" from "invalid input"?

Answer: Sometimes you want to emulate the Python interactive interpreter's behavior, where it gives you a continuation prompt when the input is incomplete (e.g. you typed the start of an "if" statement or you didn't close your parentheses or triple string quotes), but it gives you a syntax error message immediately when the input is invalid.

In Python you can use the codeop module, which approximates the parser's behavior sufficiently. IDLE uses this, for example.

The easiest w Source: CoolInterview.com
Question: How do I create a multidimensional list?

Answer: You probably tried to make a multidimensional array like this:

A = [[None] * 2] * 3

This looks correct if you print it:

>>> A
[[None, None], [None, None], [None, None]]

But when you assign a value, it shows up in multiple places:

>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]

The reason is that replicating a list with * doesn't create copies, it only creates references to the existing objects. The *3 creat Source: CoolInterview.com
Question: How to Debugging in python?

Answer: Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server.

For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML:

#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb; cgitb.enable()
print 1/0

The handler() method can Source: CoolInterview.com
Question: How do I read (or write) binary data?

Answer: or complex data formats, it's best to use the struct module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa.

For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:

import struct

f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)


The '>' in the forma Source: CoolInterview.com
Question: How can I overload constructors (or methods) in Python?

Answer: This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you'd write

class C {
C() { cout << "No arguments "; }
C(int i) { cout << "Argument is " << i << " "; }
}

in Python you have to write a single constructor that catches all cases using default arguments. For example:

class C:
def __init__(self, i=None):
if i is None:
print "No arguments"
else:
pr Source: CoolInterview.com

1 2 3 4 5 Next



India News Network
Latest 20 Questions
Payment of time- barred debt is: (a) Valid (b) Void (c) Illegal (d) Voidable
Consideration is defined in the Indian Contract Act,1872 in: (a) Section 2(f) (b) Section 2(e) (c) Section 2(g) (d) Section 2(d)
Which of the following is not an exception to the rule, "No consideration, No contract": (a) Natural love and affection (b) Compensation for involuntary services (c) Completed gift (d) Agency
Consideration must move at the desire of: (a) The promisor (b) The promisee (c) The promisor or any other party (d) Both the promisor and the promisee
An offer which is open for acceptance over a period of time is: (a) Cross Offer (b) Counter Offer (c) Standing Offer (d) Implied Offer
Specific offer can be communicated to__________ (a) All the parties of contract (b) General public in universe (c) Specific person (d) None of the above
_________ amounts to rejection of the original offer. (a) Cross offer (b) Special offer (c) Standing offer (d) Counter offer
A advertises to sell his old car by advertising in a newspaper. This offer is caleed: (a) General Offer (b) Special Offer (c) Continuing Offer (d) None of the above
In case a counter offer is made, the original offer stands: (a) Rejected (b) Accepted automatically (c) Accepted subject to certain modifications and variations (d) None of the above
In case of unenforceable contract having some technical defect, parties (a) Can sue upon it (b) Cannot sue upon it (c) Should consider it to be illegal (d) None of the above
If entire specified goods is perished before entering into contract of sale, the contract is (a) Valid (b) Void (c) Voidable (d) Cancelled
______________ contracts are also caled contracts with executed consideration. (a) Unilateral (b) Completed (c) Bilateral (d) Executory
A offers B to supply books @ Rs 100 each but B accepts the same with condition of 10% discount. This is a case of (a) Counter Offer (b) Cross Offer (c) Specific Offer (d) General Offer
_____________ is a game of chance. (a) Conditional Contract (b) Contingent Contract (c) Wagering Contract (d) Quasi Contract
There is no binding contract in case of _______ as one's offer cannot be constructed as acceptance (a) Cross Offer (b) Standing Offer (c) Counter Offer (d) Special Offer
An offer is made with an intention to have negotiation from other party. This type of offer is: (a) Invitation to offer (b) Valid offer (c) Voidable (d) None of the above
When an offer is made to the world at large, it is ____________ offer. (a) Counter (b) Special (c) General (d) None of the above
Implied contract even if not in writing or express words is perfectly _______________ if all the conditions are satisfied:- (a) Void (b) Voidable (c) Valid (d) Illegal
A specific offer can be accepted by ___________. (a) Any person (b) Any friend to offeror (c) The person to whom it is made (d) Any friend of offeree
An agreement toput a fire on a person's car is a ______: (a) Legal (b) Voidable (c) Valid (d) Illegal
Cache = 0.046875 Seconds