HACKSHALA - A BLOG FOR TECHNO GEEK
Lorem ipsum dolor sit amet, conscur adisng elit, sed do eiusmod tempor iniunt ut labore et dolore mana aliqua. Ut enim ad minim veniam, quis nostrud exetation ullco laboris nisi ut aliquip ex ea commodo coequat. Duis aute irure dolor
CYBERPUNK - UNLEASH THE TECH SAVVY IN YOU
Lorem ipsum dolor sit amet, conscur adisng elit, sed do eiusmod tempor iniunt ut labore et dolore mana aliqua. Ut enim ad minim veniam, quis nostrud exetation ullco laboris nisi ut aliquip ex ea commodo coequat. Duis aute irure dolor
CYBERPUNK - THE COMUTER NERD
Lorem ipsum dolor sit amet, conscur adisng elit, sed do eiusmod tempor iniunt ut labore et dolore mana aliqua. Ut enim ad minim veniam, quis nostrud exetation ullco laboris nisi ut aliquip ex ea commodo coequat. Duis aute irure dolor
HACK SHALA- THE PLATFORM FOR TECHNO LOVERS
Lorem ipsum dolor sit amet, conscur adisng elit, sed do eiusmod tempor iniunt ut labore et dolore mana aliqua. Ut enim ad minim veniam, quis nostrud exetation ullco laboris nisi ut aliquip ex ea commodo coequat. Duis aute irure dolor
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'
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}
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'}
namedtuples).
Lists are mutable, and their elements are usually homogeneous and are
accessed by iterating over the list.>>> 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.
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: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.
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'>
>>>
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.
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 + [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:
>>> 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
[]
append() method
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:a[len(a):] = [x].a[len(a):] = L.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
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 .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 del a[:].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
NoneUsing Lists as Stacks (LIFO)
Using Lists as Queues(FIFO):
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:
Nested List Comprehensions
zip() function would do a great job for this use case:cubes=[1,8,27,64,125]
test=['a','b','c','d','e']
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
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
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
source sendsms/bin/activate

Now install the Twilio Python helper library.
pip install twilio
Sending SMS From Python
Fire up the Python interpreter in the terminal using thepython 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
# 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. 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
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
def cmp(intellipaatlist1, intellipaatlist2):
for val in intellipaatlist1:
if val in intellipaatlist2:
returnTrue
returnFalse
For instance:
import randomize
lst = [2, 18, 8, 4];
randomize.shuffle(lst)
print “Shuffled list : “, lst
random.shuffle(list)
print “Reshuffled list : “, list
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.
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.
>>> 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.
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]
If you would set out a pass after the code, it won’t run. The syntax is pass
>>> 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’
The language also provides try-except-finally and try-except-else blocks.
>>> import intellipaat
intellipaat.trunc(4.34)
4
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.




