Python Facts
Python Facts
Python Facts
Eg: x=y=z=1
Eg: a,b=1,2
(x,y,z)=1,2,3
= assignment operator
!= not-equal-to operator
Eg:
>>> result={
... 'a':lambda x :x*5,
... 'b':lambda x:x+7,
... 'c':lambda x:x-2}
>>> result['b'](10)
17
Indentation is both boon and bane (for beginners) for python.
Use spaces instead of Tabs in scripts.
Eg:
>>> a=2
>>> a
2
>>> a=2
Traceback ( File "<interactive input>", line 1
a=2
^
IndentationError: unexpected indent
set operators
| bit-wise OR operator
Eg: 15>>1
7
Explanation: 15-1111 (in 8421 convention)
15>>1 means shifting one position left.
It becomes 0111 i.e., 7
<< right shift operator
** power of operator
/ division operator
// floor division operator (only in python3)
% modulo operator. Returns remainder of a division.
Only difference between .pyc and .pyo code is the speed with
which they are loaded.
The module compileall can create .pyc files (or .pyo files
when -O is used) for all modules in a directory.
Str.format()
>> print "This is {} and {}".format('GOOD','BAD')
This is GOOD and BAD
>> print "This is {1} and {0}".format('GOOD','BAD')
This is BAD and GOOD
>>print "This {food} is {adjective}".format(food='RICE',adjective="THE BEST ")
This RICE is THE BEST
>>> ord('a')
97
>>> chr(97)
'a'
>>> '\u011f'
'ğ'
Textual comparison
>>> 'cat'<'dog'#Alphabetic ordering
True
>>> 'Cat'<'cat'#Uppercase before lowercase
True
>>> 'Dog'<'cat'#All uppercase before lowercase
True
Note: Ordering text is called “collation”, and is a
complicated field. Python inequalities use Unicode character
numbers for collation.
x**y -x +x x%y x/y x*y x-y x+y x==y x!=y x>=y x>y x<=y x<y
not x x and y x or y
Unpacking
>>> a,b=10,7
>>> (a,b)=(a+b,a-b)#tuples
>>> a,b
(17, 3)
>>> a,b=a+b,a-b #lists
>>> a,b
(20, 14)
Lists
>>> l=[1,2,[3,4,[5,6,7]]]
>>> len(l)
3
No arithmetic operation can be performed between lists.
+ acts as a appending operator
>> a=[1,2]
>>> b=[2,3]
>>> a+b
[1, 2, 2, 3]
>>> a*3
[1, 2, 1, 2, 1, 2]