Showing posts with label Python. Show all posts
1 . New Division Functionality

>>> 1 / 2 # integer truncation (Python 2.X) 
0 
>>> 1.0 / 2.0 # returns real quotient (Python 3.x) 
0.5
 
 
2.PRINT 
 
Python2.x                                      Python3.x 
print 'hello world'     print('hello world')
 
 statement                       fumction



3.Range Function
 
In Python3.x we get a new option for range function. We can extract the first term, last term and rest of the list separately. This option was not available in Python2.x. We had to write separate code to extract these values.
 (a, *rest, b) = range(5) 
print (a) 
0 
print(b) 
4 
print(rest) 
[1, 2, 3]
 
This code section will generate a syntax error in Python2.x.
 
4.Not Equal To
 
‘<>’ symbol used in Python2.x to represent not equal to is no longer available in Python3.x. If we try it it will generate a syntax error. The symbol ‘!=’ is used instead, which was available in Python2.x along with ‘<>’.


Sequence objects may be compared to other objects with the same sequence type.

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal.

If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:


(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
Dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.


If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.



Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the in keyword.


Here is a small example using a dictionary:
>>>
>>> tel = {'jack': 4098, 'sape': 4139} # Defining a dict
>>> tel['guido'] = 4127 # adding new key-value pair in dict
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape'] # deleing  key-value pair
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys()) # list of all keys
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False



The dict() constructor builds dictionaries directly from sequences of key-value pairs:
>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])  # list of tuples
{'sape': 4139, 'jack': 4098, 'guido': 4127}


In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}


When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127} 
 
 
 
A set is an unordered collection with no duplicate elements.

Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.



Curly braces or the set() function can be used to create sets.

 Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary .

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.


A tuple consists of a number of values separated by commas, for instance:
>>>

>>> t = 12345, 54321, 'hello!'  # Packing
>>> t[0]
 12345
 >>> t  
(12345, 54321, 'hello!')
  >>> # Tuples may be nested: ...
 u = t, (1, 2, 3, 4, 5)  
>>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))  
>>> # Tuples are immutable: ...  
t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment  
>>> # but they can contain mutable objects: ...
 v = ([1, 2, 3], [3, 2, 1])
 >>> v ([1, 2, 3], [3, 2, 1])


Note :
They may be input with or without surrounding parentheses .

It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists. 



A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:


>>>
>>> empty = () 
 >>> singleton = 'hello', # <-- note trailing comma or ('hello',)
>>> len(empty)  
0 
 >>> len(singleton)  
1 
 >>> singleton ('hello',) 
 
The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>>
>>> x, y, z = t
 x=12345
y=54321
z='hello!'
 
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side.

Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.



Difference between Lists and Tuples ?

Lists : Mutable
Tuples : Immutable 

Lists can't be declared without square brackets .
Tuples can be declared  without brackets .
Eg : t = 12345, 54321, 'hello!'
( 12345, 54321, 'hello!' )


>>> t=(1)
>>> t
1
>>> type(t)
<type 'int'>
>>> t=(1,) <-- note trailing comma
>>> t
(1,)
>>> type(t)
<type 'tuple'>
>>>


Type Conversion is that which converts to data type into another for example converting a int into float converting a float into double . The Type Conversion is that which automatically converts the one data type into another but remember we can not  store a large data type into the other for example we can't store a float into int because a float is greater than int.

When a user can convert the one data type into then it is called as the type casting Remember the type Conversion is performed by the compiler but a casting is done by the user for example converting a float into int Always Remember that when we use the Type Conversion then it is called the promotion when we use the type casting means when we convert a large data type into another then it is called as the demotion when we use the type casting then we can loss some data.
Lists is a compound data types, used to group together other values written as a list of comma-separated values (items) between square brackets . Lists might contain items of different types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25] 
>>> squares [1, 4, 9, 16, 25]

Lists can be indexed and sliced:
 
>>> squares[0] # indexing returns the item 
1  
>>> squares[-1] 
25 
>>> squares[-3:] # slicing returns a new list 
[9, 16, 25]
 
 
Note : Index 0 for the first item and -1 for the last item .

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:
>>>
>>> squares[:] 
[1, 4, 9, 16, 25]


Lists also support operations like concatenation:
>>>
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
>>>
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here  
>>> 4 ** 3 # the cube of 4 is 64, not 65!  
64  
>>> cubes[3] = 64 # replace the wrong value  
>>> cubes 
[1, 8, 27, 64, 125]


Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

You can also add new items at the end of the list, by using the append() method 
>>> cubes.append(216) # add the cube of 6 
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes 
 [1, 8, 27, 64, 125, 216, 343]

 
The built-in function len() also applies to lists:
>>>
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
 
It is possible to nest lists (create lists containing other lists), for example:
>>>
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
 

More on Lists

The list data type has some more methods. Here are all of the methods of list objects:

1. list.append(x) :
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

2.list.extend(L) :
Extend the list by appending all the items in the given list L. 
Equivalent to a[len(a):] = L.
squares = [1, 4, 9, 16, 25]
cubes=[1,8,27,64,125]
squares.extend(cubes)
squares
[1, 4, 9, 16, 25, 1, 8, 27, 64, 125]

Note : Concatenation of lists
Equivalent to : squares=squares+cubes
3. list.insert(i,x):
Insert an item x at a given position . The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) i.e insert the element at the end of the list .
4.list.remove(x):
Remove the first item from the list whose value is x. It is an error if there is no such item.
5.list.pop([i]) :
Remove the item at the given position i in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position
same as del
 6.list.clear():
Remove all items from the list. Equivalent to del a[:].
Returns an empty list
Note : Supported in Python 3
7. list.index(x):
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
8.list.count(x):
Return the number of times x appears in the list.
9.list.sort([reverse=True/False])
Sort the items of the list in ascending order by default i.e reverse=False
Returns the sorted list .
sorted(list) : Return a new sorted list from the items in iterable. 
10.list.reverse()  :
Reverse the elements of the list in place.
11.list.copy() :
Return a shallow copy of the list. Equivalent to a[:].

 Note :ou might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None

Using Lists as Stacks (LIFO)

append() : Last In (add an element at the end of the list)
pop (): First Out (Remove the last element of list  without an explicit index) 

Using Lists as Queues(FIFO):

While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])



List Comprehensions:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:

squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(x, x**2) for x in range(6)]
[str(round(pi, i)) for i in range(1, 6)]
 ['3.1', '3.14', '3.142', '3.1416', '3.14159']

Nested List Comprehensions

The zip() function would do a great job for this use case:
squares = [1, 4,9, 3,16, 25]
cubes=[1,8,27,64,125]
test=['a','b','c','d','e']

 zip(squares,cubes)
 [(1, 1), (4, 8), (9, 27), (3, 64), (16, 125)]
zip(squares,cubes,test)
 [(1, 1, 'a'), (4, 8, 'b'), (9, 27, 'c'), (3, 64, 'd'), (16, 125, 'e')]

Note : Return the List of Tuples

 

 The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del can also be used to delete entire variables:
>>>
>>> del a
Referencing the name a hereafter is an error (at least until another value is assigned to it)

Note : Same as pop()

Important Notes :

Q1.Difference between del and remove() and pop() ?
del : remove the elements at the specified index
remove : remove the first specified value in the list
pop : remove the last element if no index is specified wheras in  del it gives syntax error if no index is defined .

Q2. Difference between sort and sorted?
sort : gives the same list with sorted elements
sorted : gives the shallow copy (new list ) with sorted elements

Note : List is passed in function by call by Reference i.e it will affect the original list .
 

 Using Twilio

Installing Our Dependency

Our code will use a helper library to make it easier to send text messages from Python. We are going to install the helper library from PyPI into a virtualenv. First we need to create the virtualenv. In your terminal use the following command to create a new virtualenv.

virtualenv sendsms
 
Activate the virtualenv.

source sendsms/bin/activate
 
The command prompt will change after we properly activate the virtualenv to something like this:


Now install the Twilio Python helper library.

pip install twilio
 
The helper library is now installed and we can use it with the Python code we create and execute.

Sending SMS From Python

Fire up the Python interpreter in the terminal using the python command, or create a new file named send_sms.py.

We need to grab our account credentials from the Twilio Console to connect our Python code to our Twilio account. Go to the Twilio Console and copy the Account SID and Authentication Token into your Python code.


Enter the following code into the interpreter or into the new Python file.

# we import the Twilio client from the dependency we just installed
from twilio.rest import TwilioRestClient

# the following line needs your Twilio Account SID and Auth Token
client = TwilioRestClient("ACxxxxxxxxxxxxxx", "zzzzzzzzzzzzz")

# change the "from_" number to your Twilio number and the "to" number
# to the phone number you signed up for Twilio with, or upgrade your
# account to send SMS to any phone number
client.messages.create(to="+19732644152", from_="+12023358536", 
                       body="Hello from Python!") 
 
Get Your Twilio Number 

All the lines above that start with # are comments. Once you enter that code into the interpreter or run the Python script using python send_sms.py the SMS will be sent.
In a few seconds you should see a message appear on your phone. I'm on iOS so here's how the text message I received looked.


That's it! You can add this code to any Python code to send text messages. Just keep your Auth Token secret as it'll allow anyone that has it to use your account to send and receive messages.

Using Way2SMS 


import urllib2
import cookielib
from getpass import getpass
import sys
import os
from stat import *

message = "Welcome To Python !"
number = ""

if __name__ == "__main__":   
    username = ""
    passwd = ""

    message = "+".join(message.split(' '))

 #logging into the sms site
    url ='http://site24.way2sms.com/Login1.action?'
    data = 'username='+username+'&password='+passwd+'&Submit=Sign+in'

 #For cookies

    cj= cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

 #Adding header details
    opener.addheaders=[('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120')]
    try:
        usock =opener.open(url, data)
    except IOError:
        print "error"
        #return()

    jession_id =str(cj).split('~')[1].split(' ')[0]
    send_sms_url = 'http://site24.way2sms.com/smstoss.action?'
    send_sms_data = 'ssaction=ss&Token='+jession_id+'&mobile='+number+'&message='+message+'&msgLen=136'
    opener.addheaders=[('Referer', 'http://site25.way2sms.com/sendSMS?Token='+jession_id)]
    try:
        sms_sent_page = opener.open(send_sms_url,send_sms_data)
        if sms_sent_page:
            print "Congo"
    except IOError:
        print "error"
        #return()

    print "success"
    #return ()




1. What is Python?
Python is an object oriented and open-source programming language, which supports structured and functional built-in data structures. With a placid and easy-to -understand syntax, Python allows code reuse and modularity of programs. The built-in DS in Python makes it a wonderful option for Rapid Application Development (RAD). The coding language also encourages faster editing, testing and debugging with no compilation steps.
2. What are the standard data types supported by Python?
It supports six data types:
1. Number : object stored as numeric value
2. String : object stored as string
3. Tuple : data stored in the form of sequence of immutable objects
4. Dictionary (dicts): associates one thing to another irrespective of the type of data, most useful container (called hashes in C and Java)
5. List : data stored in the form of a list sequence
6. Set (frozenset): unordered collection of distinct objects
3. Explain built-in sequence types in Python Programming?
It provides two built in sequence types-
1. Mutable Type : objects whose value can be changed after creation, example: sets, items in the list, dictionary
2. Immutable type : objects whose value cannot be changed once created, example: number, Boolean, tuple, string
4. Explain the use of iterator in Python?
Python coding uses Iterator to implement the iterator protocol, which enables traversing trough containers and group of elements like list.The two important methods include _iter_() returning the iterator object and next() method for traversal.
5.Define Python slicing ?
The process of extracting a range of elements from lists, arrays, tuples and custom Python data structures as well. It works on a general start and stop method: slice (start, stop, increment)
6. How can you compare two lists in Python?
We can simply perform it using compare function – cmp(intellipaatlist1, intellipaatlist2)
def cmp(intellipaatlist1, intellipaatlist2):
for val in intellipaatlist1:
if val in intellipaatlist2:
returnTrue
returnFalse
7. What is the use of // operator?
‘//’ is a Floor Divisionoperator, which divides two operands with the result as quotient showing only digits before decimal point.For instance, 6//3 = 2 and 6.0//3.0 = 2.0
8.Define docstring in Python with example.
A string literal occurring as the first statement (like a comment) in any module, class, function or method is referred as docstring in Python. This kind of string becomes the _doc_ special attribute of the object and provides an easy way to document a particular code segment. Most modules do contain docstrings and thus, the functions and classes extracted from the module also consist of docstrings.
9. What function randomizes the items of a list in place?
Using shuffle() function
For instance:
import randomize
lst = [2, 18, 8, 4];
randomize.shuffle(lst)
print “Shuffled list : “, lst
random.shuffle(list)
print “Reshuffled list : “, list
10. List five benefits of using Python?
1. Having the built-in data types, Python saves programmer’s time and effort from declaring variables. It has a powerful dict ionary and polymorphic list for automatic declaration. It also ensures better code reusability
2. Highly accessible and easy-to-learn for beginners and a strong ‘glue’ for advanced Professionals consisting fo several high-level modules and operations not performed by other programming languages.
3. Allows easy readability due to use of square brackets for most functions and indexes
4. Python requires no explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically.
5. Python comprises a huge standard library for most Internet platforms like Email, HTML, FTP and other WWW platforms.
11.What are the disadvantages of using Python?
1. Python is slow as compared to other programming languages. Although, this slow pace doesn’t matter much, at times, we need other language to handle performance-critical situations.
2. It is ineffective on mobile platforms; fewer mobile applications are developed using python. The main reason behind its instability on smartphones is Python’s weakest security. There are no good secure cases available for Python until now
3. Due to dynamic typing, Programmers face design restrictions while using the language. The code needs more and more testing before putting it into action since the errors pop up only during runtime.
4. Unlike JavaScript, Python’s features like concurrency and parallelism are not developed for elegant use.
12. Explain the use of split function?
The split() function in Python breaks a string into shorter strings using the defined separator. It renders a list of all words present in the string.
>>> y= ‘true,false,none’
>>> y.split(‘,’)
Result: (‘true’, ‘false’, ‘none’)
What is the use of generators in Python?
Generators are primarily used to return multiple items but one after the other. They are used for iteration in Python and for calculating large result sets. The generator function halts until the next time request is placed.
One of the best uses of generators in Python coding is implementing callback operation with reduced effort and time. They replace callback with iteration. Through the generator approach, programmers are saved from writing a separate callback function and pass it to work-function as it can applying ‘for’ loop around the generator.
13. How to create a multidimensional list in Python?
As the name suggests, a multidimensional list is the concept of a list holding another list, applying to many such lists. It can be one easily done by creating single dimensional list and filling each element with a newly created list.
14. What is lambda?
lambda is a powerful concept used in conjunction with other functions like filter(), map(), reduce(). The major use of lambda construct is
to create anonymous functions during runtime, which can be used where they are created. Such functions are actually known as throw-away functions in Python. The general syntax is lambda argument_list:expression.
For instance:
>>> def intellipaat1 = lambda i, n : i+n
>>> intellipaat(2,2)
4
Using filter()
>> intellipaat = [1, 6, 11, 21, 29, 18, 24]
>> print filter (lambda x: x%3 = = 0, intellipaat)
[6, 21, 18, 24]
15. Define Pass in Python?
The pass statement in Python is equivalent to a null operation and a placeholder, wherein nothing takes place after its execution. It is mostly used at places where you can let your code go even if it isn’t written yet.
If you would set out a pass after the code, it won’t run. The syntax is pass
16. How to perform Unit Testing in Python?
Referred to as PyUnit, the python Unit testing framework-unittest supports automated testing, seggregating test into collections, shutdown testing code and testing independence from reporting framework. The unittest module makes use of TestCase class for holding and preparing test routines and clearing them after the successful execution.
17. Define Python tools for finding bugs and performing static analysis?
. PyChecker is an excellent bug finder tool in Python, which performs static analysis unlike C/C++ and Java. It also notifies the programmers about the complexity and style of the code. In addition, there is another tool, PyLint for checking the coding standards including the code line length, variable names and whether the interfaces declared are fully executed or not.
18. How to convert a string into list?
Using the function list(string). For instance:
>>> list(‘intellipaat’) in your lines of code will return
[‘i’, ‘n’, ‘t’, ‘e’, ‘l’, ‘l’, ‘i’, ‘p’, ‘a’, ‘a’, ‘t’]
In Python, strings behave like list in various ways. Like, you can access individual characters of a string
>> > y = “intellipaat”
>>> s[2]
‘t’
19. What OS do Python support?
Linux, Windows, Mac OS X, IRIX, Compaq, Solaris
20. Name the Java implementation of Python?
Jython
21. Define docstring in Python.
A string literal occurring as the first statement (like a comment) in any module, class, function or method is referred as docstring in Python. This kind of string becomes the _doc_ special attribute of the object and provides an easy way to document a particular code segment. Most modules do contain docstrings and thus, the functions and classes extracted from the module also consist of docstrings.
22. Name the optional clauses used in a ‘try-except’ statement in Python?
While Python exception handling is a bit different from Java, the former provides an option of using a try-except clause where the programmer receives a detailed error message without termination the program. Sometimes, along with the problem, this try-except statement offers a solution to deal with the error.
The language also provides try-except-finally and try-except-else blocks.
23. How to use PYTHOPATH?
PYTHONPATH is the environment variable consisting of directories. $PYTHONPATH is used for searching the actual list of folders for libraries.
24. Define ‘self’ in Python?
self is a reference to the current instance of the class. It is just like ‘this’ in JavaScript. While we create an instance of a class, that instance has its data, which internally passes a reference to it‘self’
25. Define CGI?
Common Gateway Interface support in Python is an external gateway to interact with HTTP server and other information servers. It consists of a series of standards and instructions defining the exchange of information between a custom script and web server. The HTTP server puts all important and useful information concerning the request in the script environment and then run the script and sends it back in the form of output to the client.
26. What is PYTHONSTARTUP and how is it used?
PYTHONSTARTUP is yet another environment variable to test the Python file in the interpreter using interactive mode. The script file is executed even before the first prompt is seen. Additionally, it also allows reloading of the same script file after being modified in the external editor.
27. What is the return value of trunc() in Python?
truc() returns integer value. Uses the _trunc_ method
>>> import intellipaat
intellipaat.trunc(4.34)
4
28. How to convert a string to an object in Python?
To convert string into object, Python provides a function eval(string). It allows the Python code to run in itself
29. Is there any function to change case of all letters in the string?
Yes, Python supports a function swapcase(), which swaps the current letter case of the string. This method returns a copy of the string with the string case swapped.
30.What is pickling and unpickling in Python?
The process of Pickling relates to the Pickle module. Pickle is a general module that acquires a python object and converts it into string. It further dumps that string object into a file by using dump () function.
Pickle comprises two methods:
Dump (): dumps an object to a file object
and Load (): loads an object from a file object
Unpickling is the reacquiring process to perform retrieval of the original Python object from the stored string for reuse.
Copyright © 2013 SoftKul