Python Facts


Python Facts
Python Facts

Python is a WYSIWYG language--what you see is what you get because the way code looks in the way it runs, regardless of who coded it.

Python2 is backward compatible; whereas Python3 is backward INCOMPATIBLE.
Python supports OOPs concepts. But, in python, both private and protected modes are having same authority. This is the only limitation in python becoming complete OOP language.
Python interpreter generates byte-code, so the python applications are platform-independent.
Python runs faster than java, but slower than C language.
Python was written in C language.
Pre/Post increment/decrement like x++,x--,--x,++x, are INVALID in python
Compound operations such as +=,-=,*=,/= are VALID in Python
Python is case-sensitive i.e., variable “work” is different from variable “Work”, or “WORK
Using underscores (eg:price_at_opening) and Camel-casing (eg:PriceAtOpening)is VALID
Multiple Assignments are VALID in python.
Ex: x=y=z=1
Parallel assignment (or unpacking) is POSSIBLE in python
Eg: a,b=1,2
(x,y,z)=1,2,3
But,(x,y,z)=12 is not possible.
In python 2, Print is a statement. In python 3, print is a function.
To use print() function of python 3 in python2, place this statement in the first lines of script:
from __future__ import print_function
= assignment operator
== Operator to check value equivalence
is Operator to check identity of objects; looks at object level
in Operator to check identity of objects; looks at index level
!= not-equal-to operator
<> not-equal-to operator. Available only in python2.
# comment operator in python; called as octothorpe/pound/hash/mesh
>>> Input operator, shows readiness of interpreter. Called as chevron
^ bit-wise operator. Not power operator. Called as caret
; used to separate TWO or more statements in the same line.
‘‘‘ ’’’ or “““ ””” docstrings. Used for multiple-line comment in python scripts. Differs from using #. Appears in the output. Useful, especially, in modules.
#! Called shebang. Used as the first character in python script.
\ line-continuation operator. Used when a statement spans more than one line.
Eg: print “Udhay\
Prakash”
() used for tuples
[] used for lists
{} used for dictionaries
([]) used for sets
Switch-case condition is not defined in python. Instead, If-elif-else ladder can be used. Also, dictionary of functions can be used.
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

Running python with –t option prints warning messages when tabs and spaces are mixed inconsistently within the same program block.
Running python with –tt option turns these warning messages in to TabError exception.
raw_input() takes any input as string type.
input() takes any input type dynamically.
&&,|| are defined operators in python
and boolean operator for AND operation
or boolean operator for OR operation
not Boolean operator for NOT operation
set operators
| union operator for sets
& intersection operator for sets
  • Set difference operator
Eg: c=t-s# set c contains items in set t, but not in set s
^ Symmetric difference operator for sets
Eg: d=t^s # set d contains items in set t or set s, but not common items in both.




bitwise Operators
& bit-wise AND operator
| bit-wise OR operator
^ bit-wise XOR operator
~ bit-wise invert operator. Eg: ~5 results in -6
Bit-wise invert of x is –(x+1)
>> left shift 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.

PEP8 suggests (not mandatory) for a white space around any operator.
It is suggested to define default parameters in the last, for functions.


By default, Python source files are treated as encoded in UTF-8.
To use different encoding for source files, it must be specified in the second line, after #! line, in the script.
Format: # -*- coding: encoding -*-

When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.

range(init_value,final_value,step_size)returns integers from init_value, till final_value, in steps of step_size. It doesn’t include final_value. The step_size MUST be either positive or negative integer; not a float value.

xrange() is same as range(); but, results in values only when essential. Available only in python2.

Python supports range() data-type. So, xrange() is not required.
{} are used to create both a dictionary type and set type.
Set contains only (unrepeated) elements; whereas dictionary contains keys and elements. Keys can’t be repeated, but elements in dictionary can be repeated.

Empty set must be created as var_name=set(), instead of var_name={}. The later creates an empty dict type variable.

When the Python interpreter is invoked with -O flag, code optimized .pyo files, are generated. This optimizer only removes assert statements. When -O is used, all bytecode
is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.

Similarly, passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files.

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.

One space will be added between arguments, when print function/statement is used, in py3/py2 respectively.

Str.zfill() pads a numeric string on the left with zeros. It understands both plus and minus signs.
Eg:
>>> '23'.zfill(6)
'000023'
>>> '-3.14'.zfill(6)
'-03.14'
>>> '-3.14'.zfill(8)
'-0003.14'

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'
'ğ'

Hidden precision Limitation for python:
>>> 0.1+0.1
0.2
>>> 0.1+0.1+0.1
0.30000000000000004
>>> 0.1+0.1+0.1+0.1
0.4
It is recommended not to follow precision values.

Python can store any large number. Practically, it depends on the system memory of the machine.

Float is not exact.
>>> 4294967296.0**2
1.8446744073709552e+19
>>> 4294967296**2
18446744073709551616
1.8446744073709552×101918446744073709552000- 18446744073709551616=384
Float can be accurate upto 17 significant figures.

floating point numbers have limits both in terms of the largest and smallest numbers they can contain.
In total, floating point values have limited size and limited precision.

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.

Order of precedence for OPERATIONS:
From highest to least:

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

>>> -3**2 #** has higher precedence, compared to -
-9
>>> (-3)**2
9
All the operators except ** are left-associated, that means that the application of the
operators starts from left to right.

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)

Four spaces’ indentation indicates a “block” of code in python. This can be observed in any for, while….blocks

The immutability of tuples means they’re faster than lists.

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]

Note: All these facts are written after thorough verification. I request the readers to comment any modifications and suggestions. 

Popular posts from this blog

List of Websites to get free e-books

Online IDEs/Interpreters for python programming